From 4c02999c0a405de9043d8d1647d10f1243b84249 Mon Sep 17 00:00:00 2001 From: orosmatthew Date: Tue, 12 Mar 2024 12:37:19 -0400 Subject: [PATCH] [Shared][Web][Sandbox] Build shared in docker --- sandbox/.dockerignore | 2 + sandbox/Dockerfile | 22 +- shared/.dockerignore | 3 +- shared/.gitignore | 2 +- shared/dist/cpp.js | 2462 ------------------------- shared/dist/csharp.js | 227 --- shared/dist/java.js | 241 --- shared/dist/settings.js | 30 - shared/dist/types.js | 3778 --------------------------------------- shared/package.json | 2 +- web/Dockerfile | 22 +- 11 files changed, 28 insertions(+), 6763 deletions(-) create mode 100644 sandbox/.dockerignore delete mode 100644 shared/dist/cpp.js delete mode 100644 shared/dist/csharp.js delete mode 100644 shared/dist/java.js delete mode 100644 shared/dist/settings.js delete mode 100644 shared/dist/types.js diff --git a/sandbox/.dockerignore b/sandbox/.dockerignore new file mode 100644 index 0000000..563ba71 --- /dev/null +++ b/sandbox/.dockerignore @@ -0,0 +1,2 @@ +/node_modules +/build \ No newline at end of file diff --git a/sandbox/Dockerfile b/sandbox/Dockerfile index 6f0f273..c2229f4 100644 --- a/sandbox/Dockerfile +++ b/sandbox/Dockerfile @@ -2,9 +2,6 @@ FROM ubuntu:22.04 # Setup -RUN mkdir sandbox -WORKDIR /app/sandbox - RUN apt-get update RUN apt-get install curl -y @@ -23,21 +20,24 @@ ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true RUN git config --global user.name "Admin" RUN git config --global user.email noemail@example.com -# Prep Sandbox - -WORKDIR /app/sandbox - -COPY ./sandbox/package*.json ./ -RUN npm install -COPY ./sandbox/ . - # Prep Shared WORKDIR /app RUN mkdir shared WORKDIR /app/shared +COPY ./shared/package*.json ./ +RUN npm ci COPY ./shared . +# Prep Sandbox + +RUN mkdir sandbox +WORKDIR /app/sandbox +COPY ./sandbox/package*.json ./ +RUN npm ci +COPY ./sandbox/ . + + # Build/Run WORKDIR /app/sandbox diff --git a/shared/.dockerignore b/shared/.dockerignore index 30bc162..563ba71 100644 --- a/shared/.dockerignore +++ b/shared/.dockerignore @@ -1 +1,2 @@ -/node_modules \ No newline at end of file +/node_modules +/build \ No newline at end of file diff --git a/shared/.gitignore b/shared/.gitignore index f18af4e..8c08c51 100644 --- a/shared/.gitignore +++ b/shared/.gitignore @@ -1,2 +1,2 @@ node_modules -dist/tsconfig/tsbuildinfo +/build diff --git a/shared/dist/cpp.js b/shared/dist/cpp.js deleted file mode 100644 index 6ec29ae..0000000 --- a/shared/dist/cpp.js +++ /dev/null @@ -1,2462 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/tree-kill/index.js -var require_tree_kill = __commonJS({ - "node_modules/tree-kill/index.js"(exports2, module2) { - "use strict"; - var childProcess = require("child_process"); - var spawn2 = childProcess.spawn; - var exec2 = childProcess.exec; - module2.exports = function(pid, signal, callback) { - if (typeof signal === "function" && callback === void 0) { - callback = signal; - signal = void 0; - } - pid = parseInt(pid); - if (Number.isNaN(pid)) { - if (callback) { - return callback(new Error("pid must be a number")); - } else { - throw new Error("pid must be a number"); - } - } - var tree = {}; - var pidsToProcess = {}; - tree[pid] = []; - pidsToProcess[pid] = 1; - switch (process.platform) { - case "win32": - exec2("taskkill /pid " + pid + " /T /F", callback); - break; - case "darwin": - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("pgrep", ["-P", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - default: - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - } - }; - function killAll(tree, signal, callback) { - var killed = {}; - try { - Object.keys(tree).forEach(function(pid) { - tree[pid].forEach(function(pidpid) { - if (!killed[pidpid]) { - killPid(pidpid, signal); - killed[pidpid] = 1; - } - }); - if (!killed[pid]) { - killPid(pid, signal); - killed[pid] = 1; - } - }); - } catch (err) { - if (callback) { - return callback(err); - } else { - throw err; - } - } - if (callback) { - return callback(); - } - } - function killPid(pid, signal) { - try { - process.kill(parseInt(pid, 10), signal); - } catch (err) { - if (err.code !== "ESRCH") - throw err; - } - } - function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { - var ps = spawnChildProcessesList(parentPid); - var allData = ""; - ps.stdout.on("data", function(data) { - var data = data.toString("ascii"); - allData += data; - }); - var onClose = function(code) { - delete pidsToProcess[parentPid]; - if (code != 0) { - if (Object.keys(pidsToProcess).length == 0) { - cb(); - } - return; - } - allData.match(/\d+/g).forEach(function(pid) { - pid = parseInt(pid, 10); - tree[parentPid].push(pid); - tree[pid] = []; - pidsToProcess[pid] = 1; - buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); - }); - }; - ps.on("close", onClose); - } - } -}); - -// node_modules/universalify/index.js -var require_universalify = __commonJS({ - "node_modules/universalify/index.js"(exports2) { - "use strict"; - exports2.fromCallback = function(fn) { - return Object.defineProperty(function(...args) { - if (typeof args[args.length - 1] === "function") - fn.apply(this, args); - else { - return new Promise((resolve, reject) => { - args.push((err, res) => err != null ? reject(err) : resolve(res)); - fn.apply(this, args); - }); - } - }, "name", { value: fn.name }); - }; - exports2.fromPromise = function(fn) { - return Object.defineProperty(function(...args) { - const cb = args[args.length - 1]; - if (typeof cb !== "function") - return fn.apply(this, args); - else { - args.pop(); - fn.apply(this, args).then((r) => cb(null, r), cb); - } - }, "name", { value: fn.name }); - }; - } -}); - -// node_modules/graceful-fs/polyfills.js -var require_polyfills = __commonJS({ - "node_modules/graceful-fs/polyfills.js"(exports2, module2) { - var constants = require("constants"); - var origCwd = process.cwd; - var cwd = null; - var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform; - process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process); - return cwd; - }; - try { - process.cwd(); - } catch (er) { - } - if (typeof process.chdir === "function") { - chdir = process.chdir; - process.chdir = function(d) { - cwd = null; - chdir.call(process, d); - }; - if (Object.setPrototypeOf) - Object.setPrototypeOf(process.chdir, chdir); - } - var chdir; - module2.exports = patch; - function patch(fs2) { - if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs2); - } - if (!fs2.lutimes) { - patchLutimes(fs2); - } - fs2.chown = chownFix(fs2.chown); - fs2.fchown = chownFix(fs2.fchown); - fs2.lchown = chownFix(fs2.lchown); - fs2.chmod = chmodFix(fs2.chmod); - fs2.fchmod = chmodFix(fs2.fchmod); - fs2.lchmod = chmodFix(fs2.lchmod); - fs2.chownSync = chownFixSync(fs2.chownSync); - fs2.fchownSync = chownFixSync(fs2.fchownSync); - fs2.lchownSync = chownFixSync(fs2.lchownSync); - fs2.chmodSync = chmodFixSync(fs2.chmodSync); - fs2.fchmodSync = chmodFixSync(fs2.fchmodSync); - fs2.lchmodSync = chmodFixSync(fs2.lchmodSync); - fs2.stat = statFix(fs2.stat); - fs2.fstat = statFix(fs2.fstat); - fs2.lstat = statFix(fs2.lstat); - fs2.statSync = statFixSync(fs2.statSync); - fs2.fstatSync = statFixSync(fs2.fstatSync); - fs2.lstatSync = statFixSync(fs2.lstatSync); - if (fs2.chmod && !fs2.lchmod) { - fs2.lchmod = function(path, mode, cb) { - if (cb) - process.nextTick(cb); - }; - fs2.lchmodSync = function() { - }; - } - if (fs2.chown && !fs2.lchown) { - fs2.lchown = function(path, uid, gid, cb) { - if (cb) - process.nextTick(cb); - }; - fs2.lchownSync = function() { - }; - } - if (platform === "win32") { - fs2.rename = typeof fs2.rename !== "function" ? fs2.rename : function(fs$rename) { - function rename(from, to, cb) { - var start = Date.now(); - var backoff = 0; - fs$rename(from, to, function CB(er) { - if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) { - setTimeout(function() { - fs2.stat(to, function(stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er); - }); - }, backoff); - if (backoff < 100) - backoff += 10; - return; - } - if (cb) - cb(er); - }); - } - if (Object.setPrototypeOf) - Object.setPrototypeOf(rename, fs$rename); - return rename; - }(fs2.rename); - } - fs2.read = typeof fs2.read !== "function" ? fs2.read : function(fs$read) { - function read(fd, buffer, offset, length, position, callback_) { - var callback; - if (callback_ && typeof callback_ === "function") { - var eagCounter = 0; - callback = function(er, _, __) { - if (er && er.code === "EAGAIN" && eagCounter < 10) { - eagCounter++; - return fs$read.call(fs2, fd, buffer, offset, length, position, callback); - } - callback_.apply(this, arguments); - }; - } - return fs$read.call(fs2, fd, buffer, offset, length, position, callback); - } - if (Object.setPrototypeOf) - Object.setPrototypeOf(read, fs$read); - return read; - }(fs2.read); - fs2.readSync = typeof fs2.readSync !== "function" ? fs2.readSync : /* @__PURE__ */ function(fs$readSync) { - return function(fd, buffer, offset, length, position) { - var eagCounter = 0; - while (true) { - try { - return fs$readSync.call(fs2, fd, buffer, offset, length, position); - } catch (er) { - if (er.code === "EAGAIN" && eagCounter < 10) { - eagCounter++; - continue; - } - throw er; - } - } - }; - }(fs2.readSync); - function patchLchmod(fs3) { - fs3.lchmod = function(path, mode, callback) { - fs3.open( - path, - constants.O_WRONLY | constants.O_SYMLINK, - mode, - function(err, fd) { - if (err) { - if (callback) - callback(err); - return; - } - fs3.fchmod(fd, mode, function(err2) { - fs3.close(fd, function(err22) { - if (callback) - callback(err2 || err22); - }); - }); - } - ); - }; - fs3.lchmodSync = function(path, mode) { - var fd = fs3.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode); - var threw = true; - var ret; - try { - ret = fs3.fchmodSync(fd, mode); - threw = false; - } finally { - if (threw) { - try { - fs3.closeSync(fd); - } catch (er) { - } - } else { - fs3.closeSync(fd); - } - } - return ret; - }; - } - function patchLutimes(fs3) { - if (constants.hasOwnProperty("O_SYMLINK") && fs3.futimes) { - fs3.lutimes = function(path, at, mt, cb) { - fs3.open(path, constants.O_SYMLINK, function(er, fd) { - if (er) { - if (cb) - cb(er); - return; - } - fs3.futimes(fd, at, mt, function(er2) { - fs3.close(fd, function(er22) { - if (cb) - cb(er2 || er22); - }); - }); - }); - }; - fs3.lutimesSync = function(path, at, mt) { - var fd = fs3.openSync(path, constants.O_SYMLINK); - var ret; - var threw = true; - try { - ret = fs3.futimesSync(fd, at, mt); - threw = false; - } finally { - if (threw) { - try { - fs3.closeSync(fd); - } catch (er) { - } - } else { - fs3.closeSync(fd); - } - } - return ret; - }; - } else if (fs3.futimes) { - fs3.lutimes = function(_a, _b, _c, cb) { - if (cb) - process.nextTick(cb); - }; - fs3.lutimesSync = function() { - }; - } - } - function chmodFix(orig) { - if (!orig) - return orig; - return function(target, mode, cb) { - return orig.call(fs2, target, mode, function(er) { - if (chownErOk(er)) - er = null; - if (cb) - cb.apply(this, arguments); - }); - }; - } - function chmodFixSync(orig) { - if (!orig) - return orig; - return function(target, mode) { - try { - return orig.call(fs2, target, mode); - } catch (er) { - if (!chownErOk(er)) - throw er; - } - }; - } - function chownFix(orig) { - if (!orig) - return orig; - return function(target, uid, gid, cb) { - return orig.call(fs2, target, uid, gid, function(er) { - if (chownErOk(er)) - er = null; - if (cb) - cb.apply(this, arguments); - }); - }; - } - function chownFixSync(orig) { - if (!orig) - return orig; - return function(target, uid, gid) { - try { - return orig.call(fs2, target, uid, gid); - } catch (er) { - if (!chownErOk(er)) - throw er; - } - }; - } - function statFix(orig) { - if (!orig) - return orig; - return function(target, options, cb) { - if (typeof options === "function") { - cb = options; - options = null; - } - function callback(er, stats) { - if (stats) { - if (stats.uid < 0) - stats.uid += 4294967296; - if (stats.gid < 0) - stats.gid += 4294967296; - } - if (cb) - cb.apply(this, arguments); - } - return options ? orig.call(fs2, target, options, callback) : orig.call(fs2, target, callback); - }; - } - function statFixSync(orig) { - if (!orig) - return orig; - return function(target, options) { - var stats = options ? orig.call(fs2, target, options) : orig.call(fs2, target); - if (stats) { - if (stats.uid < 0) - stats.uid += 4294967296; - if (stats.gid < 0) - stats.gid += 4294967296; - } - return stats; - }; - } - function chownErOk(er) { - if (!er) - return true; - if (er.code === "ENOSYS") - return true; - var nonroot = !process.getuid || process.getuid() !== 0; - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true; - } - return false; - } - } - } -}); - -// node_modules/graceful-fs/legacy-streams.js -var require_legacy_streams = __commonJS({ - "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { - var Stream = require("stream").Stream; - module2.exports = legacy; - function legacy(fs2) { - return { - ReadStream, - WriteStream - }; - function ReadStream(path, options) { - if (!(this instanceof ReadStream)) - return new ReadStream(path, options); - Stream.call(this); - var self = this; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - this.flags = "r"; - this.mode = 438; - this.bufferSize = 64 * 1024; - options = options || {}; - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - if (this.encoding) - this.setEncoding(this.encoding); - if (this.start !== void 0) { - if ("number" !== typeof this.start) { - throw TypeError("start must be a Number"); - } - if (this.end === void 0) { - this.end = Infinity; - } else if ("number" !== typeof this.end) { - throw TypeError("end must be a Number"); - } - if (this.start > this.end) { - throw new Error("start must be <= end"); - } - this.pos = this.start; - } - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - fs2.open(this.path, this.flags, this.mode, function(err, fd) { - if (err) { - self.emit("error", err); - self.readable = false; - return; - } - self.fd = fd; - self.emit("open", fd); - self._read(); - }); - } - function WriteStream(path, options) { - if (!(this instanceof WriteStream)) - return new WriteStream(path, options); - Stream.call(this); - this.path = path; - this.fd = null; - this.writable = true; - this.flags = "w"; - this.encoding = "binary"; - this.mode = 438; - this.bytesWritten = 0; - options = options || {}; - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - if (this.start !== void 0) { - if ("number" !== typeof this.start) { - throw TypeError("start must be a Number"); - } - if (this.start < 0) { - throw new Error("start must be >= zero"); - } - this.pos = this.start; - } - this.busy = false; - this._queue = []; - if (this.fd === null) { - this._open = fs2.open; - this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); - this.flush(); - } - } - } - } -}); - -// node_modules/graceful-fs/clone.js -var require_clone = __commonJS({ - "node_modules/graceful-fs/clone.js"(exports2, module2) { - "use strict"; - module2.exports = clone; - var getPrototypeOf = Object.getPrototypeOf || function(obj) { - return obj.__proto__; - }; - function clone(obj) { - if (obj === null || typeof obj !== "object") - return obj; - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) }; - else - var copy = /* @__PURE__ */ Object.create(null); - Object.getOwnPropertyNames(obj).forEach(function(key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); - }); - return copy; - } - } -}); - -// node_modules/graceful-fs/graceful-fs.js -var require_graceful_fs = __commonJS({ - "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { - var fs2 = require("fs"); - var polyfills = require_polyfills(); - var legacy = require_legacy_streams(); - var clone = require_clone(); - var util2 = require("util"); - var gracefulQueue; - var previousSymbol; - if (typeof Symbol === "function" && typeof Symbol.for === "function") { - gracefulQueue = Symbol.for("graceful-fs.queue"); - previousSymbol = Symbol.for("graceful-fs.previous"); - } else { - gracefulQueue = "___graceful-fs.queue"; - previousSymbol = "___graceful-fs.previous"; - } - function noop() { - } - function publishQueue(context, queue2) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue2; - } - }); - } - var debug = noop; - if (util2.debuglog) - debug = util2.debuglog("gfs4"); - else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) - debug = function() { - var m = util2.format.apply(util2, arguments); - m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); - console.error(m); - }; - if (!fs2[gracefulQueue]) { - queue = global[gracefulQueue] || []; - publishQueue(fs2, queue); - fs2.close = function(fs$close) { - function close(fd, cb) { - return fs$close.call(fs2, fd, function(err) { - if (!err) { - resetQueue(); - } - if (typeof cb === "function") - cb.apply(this, arguments); - }); - } - Object.defineProperty(close, previousSymbol, { - value: fs$close - }); - return close; - }(fs2.close); - fs2.closeSync = function(fs$closeSync) { - function closeSync(fd) { - fs$closeSync.apply(fs2, arguments); - resetQueue(); - } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }); - return closeSync; - }(fs2.closeSync); - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { - process.on("exit", function() { - debug(fs2[gracefulQueue]); - require("assert").equal(fs2[gracefulQueue].length, 0); - }); - } - } - var queue; - if (!global[gracefulQueue]) { - publishQueue(global, fs2[gracefulQueue]); - } - module2.exports = patch(clone(fs2)); - if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs2.__patched) { - module2.exports = patch(fs2); - fs2.__patched = true; - } - function patch(fs3) { - polyfills(fs3); - fs3.gracefulify = patch; - fs3.createReadStream = createReadStream; - fs3.createWriteStream = createWriteStream; - var fs$readFile = fs3.readFile; - fs3.readFile = readFile; - function readFile(path, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$readFile(path, options, cb); - function go$readFile(path2, options2, cb2, startTime) { - return fs$readFile(path2, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - } - }); - } - } - var fs$writeFile = fs3.writeFile; - fs3.writeFile = writeFile; - function writeFile(path, data, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$writeFile(path, data, options, cb); - function go$writeFile(path2, data2, options2, cb2, startTime) { - return fs$writeFile(path2, data2, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - } - }); - } - } - var fs$appendFile = fs3.appendFile; - if (fs$appendFile) - fs3.appendFile = appendFile; - function appendFile(path, data, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$appendFile(path, data, options, cb); - function go$appendFile(path2, data2, options2, cb2, startTime) { - return fs$appendFile(path2, data2, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - } - }); - } - } - var fs$copyFile = fs3.copyFile; - if (fs$copyFile) - fs3.copyFile = copyFile; - function copyFile(src, dest, flags, cb) { - if (typeof flags === "function") { - cb = flags; - flags = 0; - } - return go$copyFile(src, dest, flags, cb); - function go$copyFile(src2, dest2, flags2, cb2, startTime) { - return fs$copyFile(src2, dest2, flags2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - } - }); - } - } - var fs$readdir = fs3.readdir; - fs3.readdir = readdir; - var noReaddirOptionVersions = /^v[0-5]\./; - function readdir(path, options, cb) { - if (typeof options === "function") - cb = options, options = null; - var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) { - return fs$readdir(path2, fs$readdirCallback( - path2, - options2, - cb2, - startTime - )); - } : function go$readdir2(path2, options2, cb2, startTime) { - return fs$readdir(path2, options2, fs$readdirCallback( - path2, - options2, - cb2, - startTime - )); - }; - return go$readdir(path, options, cb); - function fs$readdirCallback(path2, options2, cb2, startTime) { - return function(err, files) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([ - go$readdir, - [path2, options2, cb2], - err, - startTime || Date.now(), - Date.now() - ]); - else { - if (files && files.sort) - files.sort(); - if (typeof cb2 === "function") - cb2.call(this, err, files); - } - }; - } - } - if (process.version.substr(0, 4) === "v0.8") { - var legStreams = legacy(fs3); - ReadStream = legStreams.ReadStream; - WriteStream = legStreams.WriteStream; - } - var fs$ReadStream = fs3.ReadStream; - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype); - ReadStream.prototype.open = ReadStream$open; - } - var fs$WriteStream = fs3.WriteStream; - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype); - WriteStream.prototype.open = WriteStream$open; - } - Object.defineProperty(fs3, "ReadStream", { - get: function() { - return ReadStream; - }, - set: function(val) { - ReadStream = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(fs3, "WriteStream", { - get: function() { - return WriteStream; - }, - set: function(val) { - WriteStream = val; - }, - enumerable: true, - configurable: true - }); - var FileReadStream = ReadStream; - Object.defineProperty(fs3, "FileReadStream", { - get: function() { - return FileReadStream; - }, - set: function(val) { - FileReadStream = val; - }, - enumerable: true, - configurable: true - }); - var FileWriteStream = WriteStream; - Object.defineProperty(fs3, "FileWriteStream", { - get: function() { - return FileWriteStream; - }, - set: function(val) { - FileWriteStream = val; - }, - enumerable: true, - configurable: true - }); - function ReadStream(path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this; - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments); - } - function ReadStream$open() { - var that = this; - open(that.path, that.flags, that.mode, function(err, fd) { - if (err) { - if (that.autoClose) - that.destroy(); - that.emit("error", err); - } else { - that.fd = fd; - that.emit("open", fd); - that.read(); - } - }); - } - function WriteStream(path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this; - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments); - } - function WriteStream$open() { - var that = this; - open(that.path, that.flags, that.mode, function(err, fd) { - if (err) { - that.destroy(); - that.emit("error", err); - } else { - that.fd = fd; - that.emit("open", fd); - } - }); - } - function createReadStream(path, options) { - return new fs3.ReadStream(path, options); - } - function createWriteStream(path, options) { - return new fs3.WriteStream(path, options); - } - var fs$open = fs3.open; - fs3.open = open; - function open(path, flags, mode, cb) { - if (typeof mode === "function") - cb = mode, mode = null; - return go$open(path, flags, mode, cb); - function go$open(path2, flags2, mode2, cb2, startTime) { - return fs$open(path2, flags2, mode2, function(err, fd) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - } - }); - } - } - return fs3; - } - function enqueue(elem) { - debug("ENQUEUE", elem[0].name, elem[1]); - fs2[gracefulQueue].push(elem); - retry(); - } - var retryTimer; - function resetQueue() { - var now = Date.now(); - for (var i = 0; i < fs2[gracefulQueue].length; ++i) { - if (fs2[gracefulQueue][i].length > 2) { - fs2[gracefulQueue][i][3] = now; - fs2[gracefulQueue][i][4] = now; - } - } - retry(); - } - function retry() { - clearTimeout(retryTimer); - retryTimer = void 0; - if (fs2[gracefulQueue].length === 0) - return; - var elem = fs2[gracefulQueue].shift(); - var fn = elem[0]; - var args = elem[1]; - var err = elem[2]; - var startTime = elem[3]; - var lastTime = elem[4]; - if (startTime === void 0) { - debug("RETRY", fn.name, args); - fn.apply(null, args); - } else if (Date.now() - startTime >= 6e4) { - debug("TIMEOUT", fn.name, args); - var cb = args.pop(); - if (typeof cb === "function") - cb.call(null, err); - } else { - var sinceAttempt = Date.now() - lastTime; - var sinceStart = Math.max(lastTime - startTime, 1); - var desiredDelay = Math.min(sinceStart * 1.2, 100); - if (sinceAttempt >= desiredDelay) { - debug("RETRY", fn.name, args); - fn.apply(null, args.concat([startTime])); - } else { - fs2[gracefulQueue].push(elem); - } - } - if (retryTimer === void 0) { - retryTimer = setTimeout(retry, 0); - } - } - } -}); - -// node_modules/fs-extra/lib/fs/index.js -var require_fs = __commonJS({ - "node_modules/fs-extra/lib/fs/index.js"(exports2) { - "use strict"; - var u = require_universalify().fromCallback; - var fs2 = require_graceful_fs(); - var api = [ - "access", - "appendFile", - "chmod", - "chown", - "close", - "copyFile", - "fchmod", - "fchown", - "fdatasync", - "fstat", - "fsync", - "ftruncate", - "futimes", - "lchmod", - "lchown", - "link", - "lstat", - "mkdir", - "mkdtemp", - "open", - "opendir", - "readdir", - "readFile", - "readlink", - "realpath", - "rename", - "rm", - "rmdir", - "stat", - "symlink", - "truncate", - "unlink", - "utimes", - "writeFile" - ].filter((key) => { - return typeof fs2[key] === "function"; - }); - Object.assign(exports2, fs2); - api.forEach((method) => { - exports2[method] = u(fs2[method]); - }); - exports2.exists = function(filename, callback) { - if (typeof callback === "function") { - return fs2.exists(filename, callback); - } - return new Promise((resolve) => { - return fs2.exists(filename, resolve); - }); - }; - exports2.read = function(fd, buffer, offset, length, position, callback) { - if (typeof callback === "function") { - return fs2.read(fd, buffer, offset, length, position, callback); - } - return new Promise((resolve, reject) => { - fs2.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => { - if (err) - return reject(err); - resolve({ bytesRead, buffer: buffer2 }); - }); - }); - }; - exports2.write = function(fd, buffer, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs2.write(fd, buffer, ...args); - } - return new Promise((resolve, reject) => { - fs2.write(fd, buffer, ...args, (err, bytesWritten, buffer2) => { - if (err) - return reject(err); - resolve({ bytesWritten, buffer: buffer2 }); - }); - }); - }; - exports2.readv = function(fd, buffers, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs2.readv(fd, buffers, ...args); - } - return new Promise((resolve, reject) => { - fs2.readv(fd, buffers, ...args, (err, bytesRead, buffers2) => { - if (err) - return reject(err); - resolve({ bytesRead, buffers: buffers2 }); - }); - }); - }; - exports2.writev = function(fd, buffers, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs2.writev(fd, buffers, ...args); - } - return new Promise((resolve, reject) => { - fs2.writev(fd, buffers, ...args, (err, bytesWritten, buffers2) => { - if (err) - return reject(err); - resolve({ bytesWritten, buffers: buffers2 }); - }); - }); - }; - if (typeof fs2.realpath.native === "function") { - exports2.realpath.native = u(fs2.realpath.native); - } else { - process.emitWarning( - "fs.realpath.native is not a function. Is fs being monkey-patched?", - "Warning", - "fs-extra-WARN0003" - ); - } - } -}); - -// node_modules/fs-extra/lib/mkdirs/utils.js -var require_utils = __commonJS({ - "node_modules/fs-extra/lib/mkdirs/utils.js"(exports2, module2) { - "use strict"; - var path = require("path"); - module2.exports.checkPath = function checkPath(pth) { - if (process.platform === "win32") { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, "")); - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`); - error.code = "EINVAL"; - throw error; - } - } - }; - } -}); - -// node_modules/fs-extra/lib/mkdirs/make-dir.js -var require_make_dir = __commonJS({ - "node_modules/fs-extra/lib/mkdirs/make-dir.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var { checkPath } = require_utils(); - var getMode = (options) => { - const defaults = { mode: 511 }; - if (typeof options === "number") - return options; - return { ...defaults, ...options }.mode; - }; - module2.exports.makeDir = async (dir, options) => { - checkPath(dir); - return fs2.mkdir(dir, { - mode: getMode(options), - recursive: true - }); - }; - module2.exports.makeDirSync = (dir, options) => { - checkPath(dir); - return fs2.mkdirSync(dir, { - mode: getMode(options), - recursive: true - }); - }; - } -}); - -// node_modules/fs-extra/lib/mkdirs/index.js -var require_mkdirs = __commonJS({ - "node_modules/fs-extra/lib/mkdirs/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var { makeDir: _makeDir, makeDirSync } = require_make_dir(); - var makeDir = u(_makeDir); - module2.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync - }; - } -}); - -// node_modules/fs-extra/lib/path-exists/index.js -var require_path_exists = __commonJS({ - "node_modules/fs-extra/lib/path-exists/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var fs2 = require_fs(); - function pathExists(path) { - return fs2.access(path).then(() => true).catch(() => false); - } - module2.exports = { - pathExists: u(pathExists), - pathExistsSync: fs2.existsSync - }; - } -}); - -// node_modules/fs-extra/lib/util/utimes.js -var require_utimes = __commonJS({ - "node_modules/fs-extra/lib/util/utimes.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var u = require_universalify().fromPromise; - async function utimesMillis(path, atime, mtime) { - const fd = await fs2.open(path, "r+"); - let closeErr = null; - try { - await fs2.futimes(fd, atime, mtime); - } finally { - try { - await fs2.close(fd); - } catch (e) { - closeErr = e; - } - } - if (closeErr) { - throw closeErr; - } - } - function utimesMillisSync(path, atime, mtime) { - const fd = fs2.openSync(path, "r+"); - fs2.futimesSync(fd, atime, mtime); - return fs2.closeSync(fd); - } - module2.exports = { - utimesMillis: u(utimesMillis), - utimesMillisSync - }; - } -}); - -// node_modules/fs-extra/lib/util/stat.js -var require_stat = __commonJS({ - "node_modules/fs-extra/lib/util/stat.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var path = require("path"); - var u = require_universalify().fromPromise; - function getStats(src, dest, opts) { - const statFunc = opts.dereference ? (file) => fs2.stat(file, { bigint: true }) : (file) => fs2.lstat(file, { bigint: true }); - return Promise.all([ - statFunc(src), - statFunc(dest).catch((err) => { - if (err.code === "ENOENT") - return null; - throw err; - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })); - } - function getStatsSync(src, dest, opts) { - let destStat; - const statFunc = opts.dereference ? (file) => fs2.statSync(file, { bigint: true }) : (file) => fs2.lstatSync(file, { bigint: true }); - const srcStat = statFunc(src); - try { - destStat = statFunc(dest); - } catch (err) { - if (err.code === "ENOENT") - return { srcStat, destStat: null }; - throw err; - } - return { srcStat, destStat }; - } - async function checkPaths(src, dest, funcName, opts) { - const { srcStat, destStat } = await getStats(src, dest, opts); - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src); - const destBaseName = path.basename(dest); - if (funcName === "move" && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true }; - } - throw new Error("Source and destination must not be the same."); - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`); - } - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)); - } - return { srcStat, destStat }; - } - function checkPathsSync(src, dest, funcName, opts) { - const { srcStat, destStat } = getStatsSync(src, dest, opts); - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src); - const destBaseName = path.basename(dest); - if (funcName === "move" && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true }; - } - throw new Error("Source and destination must not be the same."); - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`); - } - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)); - } - return { srcStat, destStat }; - } - async function checkParentPaths(src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)); - const destParent = path.resolve(path.dirname(dest)); - if (destParent === srcParent || destParent === path.parse(destParent).root) - return; - let destStat; - try { - destStat = await fs2.stat(destParent, { bigint: true }); - } catch (err) { - if (err.code === "ENOENT") - return; - throw err; - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)); - } - return checkParentPaths(src, srcStat, destParent, funcName); - } - function checkParentPathsSync(src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)); - const destParent = path.resolve(path.dirname(dest)); - if (destParent === srcParent || destParent === path.parse(destParent).root) - return; - let destStat; - try { - destStat = fs2.statSync(destParent, { bigint: true }); - } catch (err) { - if (err.code === "ENOENT") - return; - throw err; - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)); - } - return checkParentPathsSync(src, srcStat, destParent, funcName); - } - function areIdentical(srcStat, destStat) { - return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev; - } - function isSrcSubdir(src, dest) { - const srcArr = path.resolve(src).split(path.sep).filter((i) => i); - const destArr = path.resolve(dest).split(path.sep).filter((i) => i); - return srcArr.every((cur, i) => destArr[i] === cur); - } - function errMsg(src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`; - } - module2.exports = { - // checkPaths - checkPaths: u(checkPaths), - checkPathsSync, - // checkParent - checkParentPaths: u(checkParentPaths), - checkParentPathsSync, - // Misc - isSrcSubdir, - areIdentical - }; - } -}); - -// node_modules/fs-extra/lib/copy/copy.js -var require_copy = __commonJS({ - "node_modules/fs-extra/lib/copy/copy.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var path = require("path"); - var { mkdirs } = require_mkdirs(); - var { pathExists } = require_path_exists(); - var { utimesMillis } = require_utimes(); - var stat = require_stat(); - async function copy(src, dest, opts = {}) { - if (typeof opts === "function") { - opts = { filter: opts }; - } - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - process.emitWarning( - "Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269", - "Warning", - "fs-extra-WARN0001" - ); - } - const { srcStat, destStat } = await stat.checkPaths(src, dest, "copy", opts); - await stat.checkParentPaths(src, srcStat, dest, "copy"); - const include = await runFilter(src, dest, opts); - if (!include) - return; - const destParent = path.dirname(dest); - const dirExists = await pathExists(destParent); - if (!dirExists) { - await mkdirs(destParent); - } - await getStatsAndPerformCopy(destStat, src, dest, opts); - } - async function runFilter(src, dest, opts) { - if (!opts.filter) - return true; - return opts.filter(src, dest); - } - async function getStatsAndPerformCopy(destStat, src, dest, opts) { - const statFn = opts.dereference ? fs2.stat : fs2.lstat; - const srcStat = await statFn(src); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts); - if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts); - if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts); - if (srcStat.isSocket()) - throw new Error(`Cannot copy a socket file: ${src}`); - if (srcStat.isFIFO()) - throw new Error(`Cannot copy a FIFO pipe: ${src}`); - throw new Error(`Unknown file: ${src}`); - } - async function onFile(srcStat, destStat, src, dest, opts) { - if (!destStat) - return copyFile(srcStat, src, dest, opts); - if (opts.overwrite) { - await fs2.unlink(dest); - return copyFile(srcStat, src, dest, opts); - } - if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`); - } - } - async function copyFile(srcStat, src, dest, opts) { - await fs2.copyFile(src, dest); - if (opts.preserveTimestamps) { - if (fileIsNotWritable(srcStat.mode)) { - await makeFileWritable(dest, srcStat.mode); - } - const updatedSrcStat = await fs2.stat(src); - await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime); - } - return fs2.chmod(dest, srcStat.mode); - } - function fileIsNotWritable(srcMode) { - return (srcMode & 128) === 0; - } - function makeFileWritable(dest, srcMode) { - return fs2.chmod(dest, srcMode | 128); - } - async function onDir(srcStat, destStat, src, dest, opts) { - if (!destStat) { - await fs2.mkdir(dest); - } - const items = await fs2.readdir(src); - await Promise.all(items.map(async (item) => { - const srcItem = path.join(src, item); - const destItem = path.join(dest, item); - const include = await runFilter(srcItem, destItem, opts); - if (!include) - return; - const { destStat: destStat2 } = await stat.checkPaths(srcItem, destItem, "copy", opts); - return getStatsAndPerformCopy(destStat2, srcItem, destItem, opts); - })); - if (!destStat) { - await fs2.chmod(dest, srcStat.mode); - } - } - async function onLink(destStat, src, dest, opts) { - let resolvedSrc = await fs2.readlink(src); - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs2.symlink(resolvedSrc, dest); - } - let resolvedDest = null; - try { - resolvedDest = await fs2.readlink(dest); - } catch (e) { - if (e.code === "EINVAL" || e.code === "UNKNOWN") - return fs2.symlink(resolvedSrc, dest); - throw e; - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`); - } - if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`); - } - await fs2.unlink(dest); - return fs2.symlink(resolvedSrc, dest); - } - module2.exports = copy; - } -}); - -// node_modules/fs-extra/lib/copy/copy-sync.js -var require_copy_sync = __commonJS({ - "node_modules/fs-extra/lib/copy/copy-sync.js"(exports2, module2) { - "use strict"; - var fs2 = require_graceful_fs(); - var path = require("path"); - var mkdirsSync = require_mkdirs().mkdirsSync; - var utimesMillisSync = require_utimes().utimesMillisSync; - var stat = require_stat(); - function copySync(src, dest, opts) { - if (typeof opts === "function") { - opts = { filter: opts }; - } - opts = opts || {}; - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - process.emitWarning( - "Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269", - "Warning", - "fs-extra-WARN0002" - ); - } - const { srcStat, destStat } = stat.checkPathsSync(src, dest, "copy", opts); - stat.checkParentPathsSync(src, srcStat, dest, "copy"); - if (opts.filter && !opts.filter(src, dest)) - return; - const destParent = path.dirname(dest); - if (!fs2.existsSync(destParent)) - mkdirsSync(destParent); - return getStats(destStat, src, dest, opts); - } - function getStats(destStat, src, dest, opts) { - const statSync = opts.dereference ? fs2.statSync : fs2.lstatSync; - const srcStat = statSync(src); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts); - else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts); - else if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts); - else if (srcStat.isSocket()) - throw new Error(`Cannot copy a socket file: ${src}`); - else if (srcStat.isFIFO()) - throw new Error(`Cannot copy a FIFO pipe: ${src}`); - throw new Error(`Unknown file: ${src}`); - } - function onFile(srcStat, destStat, src, dest, opts) { - if (!destStat) - return copyFile(srcStat, src, dest, opts); - return mayCopyFile(srcStat, src, dest, opts); - } - function mayCopyFile(srcStat, src, dest, opts) { - if (opts.overwrite) { - fs2.unlinkSync(dest); - return copyFile(srcStat, src, dest, opts); - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`); - } - } - function copyFile(srcStat, src, dest, opts) { - fs2.copyFileSync(src, dest); - if (opts.preserveTimestamps) - handleTimestamps(srcStat.mode, src, dest); - return setDestMode(dest, srcStat.mode); - } - function handleTimestamps(srcMode, src, dest) { - if (fileIsNotWritable(srcMode)) - makeFileWritable(dest, srcMode); - return setDestTimestamps(src, dest); - } - function fileIsNotWritable(srcMode) { - return (srcMode & 128) === 0; - } - function makeFileWritable(dest, srcMode) { - return setDestMode(dest, srcMode | 128); - } - function setDestMode(dest, srcMode) { - return fs2.chmodSync(dest, srcMode); - } - function setDestTimestamps(src, dest) { - const updatedSrcStat = fs2.statSync(src); - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime); - } - function onDir(srcStat, destStat, src, dest, opts) { - if (!destStat) - return mkDirAndCopy(srcStat.mode, src, dest, opts); - return copyDir(src, dest, opts); - } - function mkDirAndCopy(srcMode, src, dest, opts) { - fs2.mkdirSync(dest); - copyDir(src, dest, opts); - return setDestMode(dest, srcMode); - } - function copyDir(src, dest, opts) { - fs2.readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts)); - } - function copyDirItem(item, src, dest, opts) { - const srcItem = path.join(src, item); - const destItem = path.join(dest, item); - if (opts.filter && !opts.filter(srcItem, destItem)) - return; - const { destStat } = stat.checkPathsSync(srcItem, destItem, "copy", opts); - return getStats(destStat, srcItem, destItem, opts); - } - function onLink(destStat, src, dest, opts) { - let resolvedSrc = fs2.readlinkSync(src); - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs2.symlinkSync(resolvedSrc, dest); - } else { - let resolvedDest; - try { - resolvedDest = fs2.readlinkSync(dest); - } catch (err) { - if (err.code === "EINVAL" || err.code === "UNKNOWN") - return fs2.symlinkSync(resolvedSrc, dest); - throw err; - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`); - } - if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`); - } - return copyLink(resolvedSrc, dest); - } - } - function copyLink(resolvedSrc, dest) { - fs2.unlinkSync(dest); - return fs2.symlinkSync(resolvedSrc, dest); - } - module2.exports = copySync; - } -}); - -// node_modules/fs-extra/lib/copy/index.js -var require_copy2 = __commonJS({ - "node_modules/fs-extra/lib/copy/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - module2.exports = { - copy: u(require_copy()), - copySync: require_copy_sync() - }; - } -}); - -// node_modules/fs-extra/lib/remove/index.js -var require_remove = __commonJS({ - "node_modules/fs-extra/lib/remove/index.js"(exports2, module2) { - "use strict"; - var fs2 = require_graceful_fs(); - var u = require_universalify().fromCallback; - function remove(path, callback) { - fs2.rm(path, { recursive: true, force: true }, callback); - } - function removeSync2(path) { - fs2.rmSync(path, { recursive: true, force: true }); - } - module2.exports = { - remove: u(remove), - removeSync: removeSync2 - }; - } -}); - -// node_modules/fs-extra/lib/empty/index.js -var require_empty = __commonJS({ - "node_modules/fs-extra/lib/empty/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var fs2 = require_fs(); - var path = require("path"); - var mkdir = require_mkdirs(); - var remove = require_remove(); - var emptyDir = u(async function emptyDir2(dir) { - let items; - try { - items = await fs2.readdir(dir); - } catch { - return mkdir.mkdirs(dir); - } - return Promise.all(items.map((item) => remove.remove(path.join(dir, item)))); - }); - function emptyDirSync(dir) { - let items; - try { - items = fs2.readdirSync(dir); - } catch { - return mkdir.mkdirsSync(dir); - } - items.forEach((item) => { - item = path.join(dir, item); - remove.removeSync(item); - }); - } - module2.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir - }; - } -}); - -// node_modules/fs-extra/lib/ensure/file.js -var require_file = __commonJS({ - "node_modules/fs-extra/lib/ensure/file.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var path = require("path"); - var fs2 = require_fs(); - var mkdir = require_mkdirs(); - async function createFile(file) { - let stats; - try { - stats = await fs2.stat(file); - } catch { - } - if (stats && stats.isFile()) - return; - const dir = path.dirname(file); - let dirStats = null; - try { - dirStats = await fs2.stat(dir); - } catch (err) { - if (err.code === "ENOENT") { - await mkdir.mkdirs(dir); - await fs2.writeFile(file, ""); - return; - } else { - throw err; - } - } - if (dirStats.isDirectory()) { - await fs2.writeFile(file, ""); - } else { - await fs2.readdir(dir); - } - } - function createFileSync(file) { - let stats; - try { - stats = fs2.statSync(file); - } catch { - } - if (stats && stats.isFile()) - return; - const dir = path.dirname(file); - try { - if (!fs2.statSync(dir).isDirectory()) { - fs2.readdirSync(dir); - } - } catch (err) { - if (err && err.code === "ENOENT") - mkdir.mkdirsSync(dir); - else - throw err; - } - fs2.writeFileSync(file, ""); - } - module2.exports = { - createFile: u(createFile), - createFileSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/link.js -var require_link = __commonJS({ - "node_modules/fs-extra/lib/ensure/link.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var path = require("path"); - var fs2 = require_fs(); - var mkdir = require_mkdirs(); - var { pathExists } = require_path_exists(); - var { areIdentical } = require_stat(); - async function createLink(srcpath, dstpath) { - let dstStat; - try { - dstStat = await fs2.lstat(dstpath); - } catch { - } - let srcStat; - try { - srcStat = await fs2.lstat(srcpath); - } catch (err) { - err.message = err.message.replace("lstat", "ensureLink"); - throw err; - } - if (dstStat && areIdentical(srcStat, dstStat)) - return; - const dir = path.dirname(dstpath); - const dirExists = await pathExists(dir); - if (!dirExists) { - await mkdir.mkdirs(dir); - } - await fs2.link(srcpath, dstpath); - } - function createLinkSync(srcpath, dstpath) { - let dstStat; - try { - dstStat = fs2.lstatSync(dstpath); - } catch { - } - try { - const srcStat = fs2.lstatSync(srcpath); - if (dstStat && areIdentical(srcStat, dstStat)) - return; - } catch (err) { - err.message = err.message.replace("lstat", "ensureLink"); - throw err; - } - const dir = path.dirname(dstpath); - const dirExists = fs2.existsSync(dir); - if (dirExists) - return fs2.linkSync(srcpath, dstpath); - mkdir.mkdirsSync(dir); - return fs2.linkSync(srcpath, dstpath); - } - module2.exports = { - createLink: u(createLink), - createLinkSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink-paths.js -var require_symlink_paths = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink-paths.js"(exports2, module2) { - "use strict"; - var path = require("path"); - var fs2 = require_fs(); - var { pathExists } = require_path_exists(); - var u = require_universalify().fromPromise; - async function symlinkPaths(srcpath, dstpath) { - if (path.isAbsolute(srcpath)) { - try { - await fs2.lstat(srcpath); - } catch (err) { - err.message = err.message.replace("lstat", "ensureSymlink"); - throw err; - } - return { - toCwd: srcpath, - toDst: srcpath - }; - } - const dstdir = path.dirname(dstpath); - const relativeToDst = path.join(dstdir, srcpath); - const exists = await pathExists(relativeToDst); - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - }; - } - try { - await fs2.lstat(srcpath); - } catch (err) { - err.message = err.message.replace("lstat", "ensureSymlink"); - throw err; - } - return { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - }; - } - function symlinkPathsSync(srcpath, dstpath) { - if (path.isAbsolute(srcpath)) { - const exists2 = fs2.existsSync(srcpath); - if (!exists2) - throw new Error("absolute srcpath does not exist"); - return { - toCwd: srcpath, - toDst: srcpath - }; - } - const dstdir = path.dirname(dstpath); - const relativeToDst = path.join(dstdir, srcpath); - const exists = fs2.existsSync(relativeToDst); - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - }; - } - const srcExists = fs2.existsSync(srcpath); - if (!srcExists) - throw new Error("relative srcpath does not exist"); - return { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - }; - } - module2.exports = { - symlinkPaths: u(symlinkPaths), - symlinkPathsSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink-type.js -var require_symlink_type = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink-type.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var u = require_universalify().fromPromise; - async function symlinkType(srcpath, type) { - if (type) - return type; - let stats; - try { - stats = await fs2.lstat(srcpath); - } catch { - return "file"; - } - return stats && stats.isDirectory() ? "dir" : "file"; - } - function symlinkTypeSync(srcpath, type) { - if (type) - return type; - let stats; - try { - stats = fs2.lstatSync(srcpath); - } catch { - return "file"; - } - return stats && stats.isDirectory() ? "dir" : "file"; - } - module2.exports = { - symlinkType: u(symlinkType), - symlinkTypeSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink.js -var require_symlink = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var path = require("path"); - var fs2 = require_fs(); - var { mkdirs, mkdirsSync } = require_mkdirs(); - var { symlinkPaths, symlinkPathsSync } = require_symlink_paths(); - var { symlinkType, symlinkTypeSync } = require_symlink_type(); - var { pathExists } = require_path_exists(); - var { areIdentical } = require_stat(); - async function createSymlink(srcpath, dstpath, type) { - let stats; - try { - stats = await fs2.lstat(dstpath); - } catch { - } - if (stats && stats.isSymbolicLink()) { - const [srcStat, dstStat] = await Promise.all([ - fs2.stat(srcpath), - fs2.stat(dstpath) - ]); - if (areIdentical(srcStat, dstStat)) - return; - } - const relative = await symlinkPaths(srcpath, dstpath); - srcpath = relative.toDst; - const toType = await symlinkType(relative.toCwd, type); - const dir = path.dirname(dstpath); - if (!await pathExists(dir)) { - await mkdirs(dir); - } - return fs2.symlink(srcpath, dstpath, toType); - } - function createSymlinkSync(srcpath, dstpath, type) { - let stats; - try { - stats = fs2.lstatSync(dstpath); - } catch { - } - if (stats && stats.isSymbolicLink()) { - const srcStat = fs2.statSync(srcpath); - const dstStat = fs2.statSync(dstpath); - if (areIdentical(srcStat, dstStat)) - return; - } - const relative = symlinkPathsSync(srcpath, dstpath); - srcpath = relative.toDst; - type = symlinkTypeSync(relative.toCwd, type); - const dir = path.dirname(dstpath); - const exists = fs2.existsSync(dir); - if (exists) - return fs2.symlinkSync(srcpath, dstpath, type); - mkdirsSync(dir); - return fs2.symlinkSync(srcpath, dstpath, type); - } - module2.exports = { - createSymlink: u(createSymlink), - createSymlinkSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/index.js -var require_ensure = __commonJS({ - "node_modules/fs-extra/lib/ensure/index.js"(exports2, module2) { - "use strict"; - var { createFile, createFileSync } = require_file(); - var { createLink, createLinkSync } = require_link(); - var { createSymlink, createSymlinkSync } = require_symlink(); - module2.exports = { - // file - createFile, - createFileSync, - ensureFile: createFile, - ensureFileSync: createFileSync, - // link - createLink, - createLinkSync, - ensureLink: createLink, - ensureLinkSync: createLinkSync, - // symlink - createSymlink, - createSymlinkSync, - ensureSymlink: createSymlink, - ensureSymlinkSync: createSymlinkSync - }; - } -}); - -// node_modules/jsonfile/utils.js -var require_utils2 = __commonJS({ - "node_modules/jsonfile/utils.js"(exports2, module2) { - function stringify(obj, { EOL = "\n", finalEOL = true, replacer = null, spaces } = {}) { - const EOF = finalEOL ? EOL : ""; - const str = JSON.stringify(obj, replacer, spaces); - return str.replace(/\n/g, EOL) + EOF; - } - function stripBom(content) { - if (Buffer.isBuffer(content)) - content = content.toString("utf8"); - return content.replace(/^\uFEFF/, ""); - } - module2.exports = { stringify, stripBom }; - } -}); - -// node_modules/jsonfile/index.js -var require_jsonfile = __commonJS({ - "node_modules/jsonfile/index.js"(exports2, module2) { - var _fs; - try { - _fs = require_graceful_fs(); - } catch (_) { - _fs = require("fs"); - } - var universalify = require_universalify(); - var { stringify, stripBom } = require_utils2(); - async function _readFile(file, options = {}) { - if (typeof options === "string") { - options = { encoding: options }; - } - const fs2 = options.fs || _fs; - const shouldThrow = "throws" in options ? options.throws : true; - let data = await universalify.fromCallback(fs2.readFile)(file, options); - data = stripBom(data); - let obj; - try { - obj = JSON.parse(data, options ? options.reviver : null); - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err; - } else { - return null; - } - } - return obj; - } - var readFile = universalify.fromPromise(_readFile); - function readFileSync(file, options = {}) { - if (typeof options === "string") { - options = { encoding: options }; - } - const fs2 = options.fs || _fs; - const shouldThrow = "throws" in options ? options.throws : true; - try { - let content = fs2.readFileSync(file, options); - content = stripBom(content); - return JSON.parse(content, options.reviver); - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err; - } else { - return null; - } - } - } - async function _writeFile(file, obj, options = {}) { - const fs2 = options.fs || _fs; - const str = stringify(obj, options); - await universalify.fromCallback(fs2.writeFile)(file, str, options); - } - var writeFile = universalify.fromPromise(_writeFile); - function writeFileSync(file, obj, options = {}) { - const fs2 = options.fs || _fs; - const str = stringify(obj, options); - return fs2.writeFileSync(file, str, options); - } - var jsonfile = { - readFile, - readFileSync, - writeFile, - writeFileSync - }; - module2.exports = jsonfile; - } -}); - -// node_modules/fs-extra/lib/json/jsonfile.js -var require_jsonfile2 = __commonJS({ - "node_modules/fs-extra/lib/json/jsonfile.js"(exports2, module2) { - "use strict"; - var jsonFile = require_jsonfile(); - module2.exports = { - // jsonfile exports - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync - }; - } -}); - -// node_modules/fs-extra/lib/output-file/index.js -var require_output_file = __commonJS({ - "node_modules/fs-extra/lib/output-file/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var fs2 = require_fs(); - var path = require("path"); - var mkdir = require_mkdirs(); - var pathExists = require_path_exists().pathExists; - async function outputFile(file, data, encoding = "utf-8") { - const dir = path.dirname(file); - if (!await pathExists(dir)) { - await mkdir.mkdirs(dir); - } - return fs2.writeFile(file, data, encoding); - } - function outputFileSync(file, ...args) { - const dir = path.dirname(file); - if (!fs2.existsSync(dir)) { - mkdir.mkdirsSync(dir); - } - fs2.writeFileSync(file, ...args); - } - module2.exports = { - outputFile: u(outputFile), - outputFileSync - }; - } -}); - -// node_modules/fs-extra/lib/json/output-json.js -var require_output_json = __commonJS({ - "node_modules/fs-extra/lib/json/output-json.js"(exports2, module2) { - "use strict"; - var { stringify } = require_utils2(); - var { outputFile } = require_output_file(); - async function outputJson(file, data, options = {}) { - const str = stringify(data, options); - await outputFile(file, str, options); - } - module2.exports = outputJson; - } -}); - -// node_modules/fs-extra/lib/json/output-json-sync.js -var require_output_json_sync = __commonJS({ - "node_modules/fs-extra/lib/json/output-json-sync.js"(exports2, module2) { - "use strict"; - var { stringify } = require_utils2(); - var { outputFileSync } = require_output_file(); - function outputJsonSync(file, data, options) { - const str = stringify(data, options); - outputFileSync(file, str, options); - } - module2.exports = outputJsonSync; - } -}); - -// node_modules/fs-extra/lib/json/index.js -var require_json = __commonJS({ - "node_modules/fs-extra/lib/json/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var jsonFile = require_jsonfile2(); - jsonFile.outputJson = u(require_output_json()); - jsonFile.outputJsonSync = require_output_json_sync(); - jsonFile.outputJSON = jsonFile.outputJson; - jsonFile.outputJSONSync = jsonFile.outputJsonSync; - jsonFile.writeJSON = jsonFile.writeJson; - jsonFile.writeJSONSync = jsonFile.writeJsonSync; - jsonFile.readJSON = jsonFile.readJson; - jsonFile.readJSONSync = jsonFile.readJsonSync; - module2.exports = jsonFile; - } -}); - -// node_modules/fs-extra/lib/move/move.js -var require_move = __commonJS({ - "node_modules/fs-extra/lib/move/move.js"(exports2, module2) { - "use strict"; - var fs2 = require_fs(); - var path = require("path"); - var { copy } = require_copy2(); - var { remove } = require_remove(); - var { mkdirp } = require_mkdirs(); - var { pathExists } = require_path_exists(); - var stat = require_stat(); - async function move(src, dest, opts = {}) { - const overwrite = opts.overwrite || opts.clobber || false; - const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, "move", opts); - await stat.checkParentPaths(src, srcStat, dest, "move"); - const destParent = path.dirname(dest); - const parsedParentPath = path.parse(destParent); - if (parsedParentPath.root !== destParent) { - await mkdirp(destParent); - } - return doRename(src, dest, overwrite, isChangingCase); - } - async function doRename(src, dest, overwrite, isChangingCase) { - if (!isChangingCase) { - if (overwrite) { - await remove(dest); - } else if (await pathExists(dest)) { - throw new Error("dest already exists."); - } - } - try { - await fs2.rename(src, dest); - } catch (err) { - if (err.code !== "EXDEV") { - throw err; - } - await moveAcrossDevice(src, dest, overwrite); - } - } - async function moveAcrossDevice(src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true, - preserveTimestamps: true - }; - await copy(src, dest, opts); - return remove(src); - } - module2.exports = move; - } -}); - -// node_modules/fs-extra/lib/move/move-sync.js -var require_move_sync = __commonJS({ - "node_modules/fs-extra/lib/move/move-sync.js"(exports2, module2) { - "use strict"; - var fs2 = require_graceful_fs(); - var path = require("path"); - var copySync = require_copy2().copySync; - var removeSync2 = require_remove().removeSync; - var mkdirpSync = require_mkdirs().mkdirpSync; - var stat = require_stat(); - function moveSync(src, dest, opts) { - opts = opts || {}; - const overwrite = opts.overwrite || opts.clobber || false; - const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, "move", opts); - stat.checkParentPathsSync(src, srcStat, dest, "move"); - if (!isParentRoot(dest)) - mkdirpSync(path.dirname(dest)); - return doRename(src, dest, overwrite, isChangingCase); - } - function isParentRoot(dest) { - const parent = path.dirname(dest); - const parsedPath = path.parse(parent); - return parsedPath.root === parent; - } - function doRename(src, dest, overwrite, isChangingCase) { - if (isChangingCase) - return rename(src, dest, overwrite); - if (overwrite) { - removeSync2(dest); - return rename(src, dest, overwrite); - } - if (fs2.existsSync(dest)) - throw new Error("dest already exists."); - return rename(src, dest, overwrite); - } - function rename(src, dest, overwrite) { - try { - fs2.renameSync(src, dest); - } catch (err) { - if (err.code !== "EXDEV") - throw err; - return moveAcrossDevice(src, dest, overwrite); - } - } - function moveAcrossDevice(src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true, - preserveTimestamps: true - }; - copySync(src, dest, opts); - return removeSync2(src); - } - module2.exports = moveSync; - } -}); - -// node_modules/fs-extra/lib/move/index.js -var require_move2 = __commonJS({ - "node_modules/fs-extra/lib/move/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - module2.exports = { - move: u(require_move()), - moveSync: require_move_sync() - }; - } -}); - -// node_modules/fs-extra/lib/index.js -var require_lib = __commonJS({ - "node_modules/fs-extra/lib/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - // Export promiseified graceful-fs: - ...require_fs(), - // Export extra methods: - ...require_copy2(), - ...require_empty(), - ...require_ensure(), - ...require_json(), - ...require_mkdirs(), - ...require_move2(), - ...require_output_file(), - ...require_path_exists(), - ...require_remove() - }; - } -}); - -// submission-runner/cpp.cts -var cpp_exports = {}; -__export(cpp_exports, { - runCpp: () => runCpp -}); -module.exports = __toCommonJS(cpp_exports); -var import_path = require("path"); -var import_child_process = require("child_process"); -var util = __toESM(require("util")); - -// submission-runner/settings.cts -var timeoutSeconds = 30; - -// submission-runner/cpp.cts -var import_tree_kill = __toESM(require_tree_kill()); -var os = __toESM(require("os")); -var fs = __toESM(require_lib()); -var execPromise = util.promisify(import_child_process.exec); -var runCpp = async function(params) { - const tmpDir = os.tmpdir(); - const buildDir = (0, import_path.join)(tmpDir, "bwcontest-cpp"); - if (fs.existsSync(buildDir)) { - fs.removeSync(buildDir); - } - fs.mkdirSync(buildDir); - console.log(`- BUILD: ${params.problemName}`); - const configureCommand = `cmake -S ${params.srcDir} -B ${buildDir}`; - try { - await execPromise(configureCommand); - } catch (e) { - const buildErrorText = e?.toString() ?? "Unknown build errors."; - console.log("Build errors: " + buildErrorText); - return { - success: false, - runResult: { kind: "CompileFailed", resultKindReason: buildErrorText } - }; - } - const compileCommand = `cmake --build ${buildDir} --target ${params.problemName}`; - try { - await execPromise(compileCommand); - } catch (e) { - const buildErrorText = e?.toString() ?? "Unknown build errors."; - console.log("Build errors: " + buildErrorText); - return { - success: false, - runResult: { kind: "CompileFailed", resultKindReason: buildErrorText } - }; - } - console.log(`- RUN: ${params.problemName}`); - let runCommand = ""; - if (params.cppPlatform === "VisualStudio") { - runCommand = `${(0, import_path.join)(buildDir, "Debug", `${params.problemName}.exe`)}`; - } else { - runCommand = `${(0, import_path.join)(buildDir, params.problemName)}`; - } - try { - let outputBuffer = ""; - const child = (0, import_child_process.spawn)(runCommand, { shell: true }); - child.stdout.setEncoding("utf8"); - child.stdout.on("data", (data) => { - outputBuffer += data.toString(); - }); - child.stderr.setEncoding("utf8"); - child.stderr.on("data", (data) => { - outputBuffer += data.toString(); - }); - const runStartTime = performance.now(); - child.stdin.write(params.input); - child.stdin.end(); - let timeLimitExceeded = false; - let completedNormally = false; - return { - success: true, - runResult: new Promise((resolve) => { - child.on("close", () => { - completedNormally = !timeLimitExceeded; - const runEndTime = performance.now(); - const runtimeMilliseconds = Math.floor(runEndTime - runStartTime); - if (completedNormally) { - clearTimeout(timeoutHandle); - resolve({ - kind: "Completed", - output: outputBuffer, - exitCode: child.exitCode, - runtimeMilliseconds - }); - } else { - console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`); - resolve({ - kind: "TimeLimitExceeded", - output: outputBuffer, - resultKindReason: `Timeout after ${timeoutSeconds} seconds` - }); - } - }); - const timeoutHandle = setTimeout(() => { - if (completedNormally) { - return; - } - console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`); - timeLimitExceeded = true; - child.stdin.end(); - child.stdin.destroy(); - child.stdout.destroy(); - child.stderr.destroy(); - child.kill("SIGKILL"); - }, timeoutSeconds * 1e3); - }), - killFunc() { - if (child.pid !== void 0) { - if (!completedNormally && !timeLimitExceeded) { - (0, import_tree_kill.default)(child.pid); - params.outputCallback?.("\n[Manually stopped]"); - } - } - } - }; - } catch (error) { - return { success: false, runResult: { kind: "RunError" } }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - runCpp -}); diff --git a/shared/dist/csharp.js b/shared/dist/csharp.js deleted file mode 100644 index 069178e..0000000 --- a/shared/dist/csharp.js +++ /dev/null @@ -1,227 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/tree-kill/index.js -var require_tree_kill = __commonJS({ - "node_modules/tree-kill/index.js"(exports2, module2) { - "use strict"; - var childProcess = require("child_process"); - var spawn2 = childProcess.spawn; - var exec = childProcess.exec; - module2.exports = function(pid, signal, callback) { - if (typeof signal === "function" && callback === void 0) { - callback = signal; - signal = void 0; - } - pid = parseInt(pid); - if (Number.isNaN(pid)) { - if (callback) { - return callback(new Error("pid must be a number")); - } else { - throw new Error("pid must be a number"); - } - } - var tree = {}; - var pidsToProcess = {}; - tree[pid] = []; - pidsToProcess[pid] = 1; - switch (process.platform) { - case "win32": - exec("taskkill /pid " + pid + " /T /F", callback); - break; - case "darwin": - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("pgrep", ["-P", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - default: - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - } - }; - function killAll(tree, signal, callback) { - var killed = {}; - try { - Object.keys(tree).forEach(function(pid) { - tree[pid].forEach(function(pidpid) { - if (!killed[pidpid]) { - killPid(pidpid, signal); - killed[pidpid] = 1; - } - }); - if (!killed[pid]) { - killPid(pid, signal); - killed[pid] = 1; - } - }); - } catch (err) { - if (callback) { - return callback(err); - } else { - throw err; - } - } - if (callback) { - return callback(); - } - } - function killPid(pid, signal) { - try { - process.kill(parseInt(pid, 10), signal); - } catch (err) { - if (err.code !== "ESRCH") - throw err; - } - } - function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { - var ps = spawnChildProcessesList(parentPid); - var allData = ""; - ps.stdout.on("data", function(data) { - var data = data.toString("ascii"); - allData += data; - }); - var onClose = function(code) { - delete pidsToProcess[parentPid]; - if (code != 0) { - if (Object.keys(pidsToProcess).length == 0) { - cb(); - } - return; - } - allData.match(/\d+/g).forEach(function(pid) { - pid = parseInt(pid, 10); - tree[parentPid].push(pid); - tree[pid] = []; - pidsToProcess[pid] = 1; - buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); - }); - }; - ps.on("close", onClose); - } - } -}); - -// submission-runner/csharp.cts -var csharp_exports = {}; -__export(csharp_exports, { - runCSharp: () => runCSharp -}); -module.exports = __toCommonJS(csharp_exports); -var import_child_process = require("child_process"); -var import_tree_kill = __toESM(require_tree_kill()); - -// submission-runner/settings.cts -var timeoutSeconds = 30; - -// submission-runner/csharp.cts -var runCSharp = async function(params) { - console.log(`- RUN: ${params.srcDir}`); - const child = (0, import_child_process.spawn)("dotnet run", { shell: true, cwd: params.srcDir }); - try { - let outputBuffer = ""; - child.stdout.setEncoding("utf8"); - child.stdout.on("data", (data) => { - outputBuffer += data.toString(); - params.outputCallback?.(data.toString()); - }); - child.stderr.setEncoding("utf8"); - child.stderr.on("data", (data) => { - outputBuffer += data.toString(); - params.outputCallback?.(data.toString()); - }); - const runStartTime = performance.now(); - child.stdin.write(params.input); - child.stdin.end(); - let timeLimitExceeded = false; - let completedNormally = false; - return { - success: true, - runResult: new Promise((resolve) => { - child.on("close", () => { - completedNormally = !timeLimitExceeded; - const runEndTime = performance.now(); - const runtimeMilliseconds = Math.floor(runEndTime - runStartTime); - if (completedNormally) { - clearTimeout(timeoutHandle); - resolve({ - kind: "Completed", - output: outputBuffer, - exitCode: child.exitCode, - runtimeMilliseconds - }); - } else { - console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`); - resolve({ - kind: "TimeLimitExceeded", - output: outputBuffer, - resultKindReason: `Timeout after ${timeoutSeconds} seconds` - }); - } - }); - const timeoutHandle = setTimeout(() => { - if (completedNormally) { - return; - } - console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`); - timeLimitExceeded = true; - child.stdin.end(); - child.stdin.destroy(); - child.stdout.destroy(); - child.stderr.destroy(); - if (child.pid !== void 0) { - (0, import_tree_kill.default)(child.pid); - } - }, timeoutSeconds * 1e3); - }), - killFunc() { - if (child.pid !== void 0) { - if (!completedNormally && !timeLimitExceeded) { - (0, import_tree_kill.default)(child.pid); - params.outputCallback?.("\n[Manually stopped]"); - } - } - } - }; - } catch (error) { - return { success: false, runResult: { kind: "RunError" } }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - runCSharp -}); diff --git a/shared/dist/java.js b/shared/dist/java.js deleted file mode 100644 index 5da3e5f..0000000 --- a/shared/dist/java.js +++ /dev/null @@ -1,241 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/tree-kill/index.js -var require_tree_kill = __commonJS({ - "node_modules/tree-kill/index.js"(exports2, module2) { - "use strict"; - var childProcess = require("child_process"); - var spawn2 = childProcess.spawn; - var exec2 = childProcess.exec; - module2.exports = function(pid, signal, callback) { - if (typeof signal === "function" && callback === void 0) { - callback = signal; - signal = void 0; - } - pid = parseInt(pid); - if (Number.isNaN(pid)) { - if (callback) { - return callback(new Error("pid must be a number")); - } else { - throw new Error("pid must be a number"); - } - } - var tree = {}; - var pidsToProcess = {}; - tree[pid] = []; - pidsToProcess[pid] = 1; - switch (process.platform) { - case "win32": - exec2("taskkill /pid " + pid + " /T /F", callback); - break; - case "darwin": - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("pgrep", ["-P", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - default: - buildProcessTree(pid, tree, pidsToProcess, function(parentPid) { - return spawn2("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]); - }, function() { - killAll(tree, signal, callback); - }); - break; - } - }; - function killAll(tree, signal, callback) { - var killed = {}; - try { - Object.keys(tree).forEach(function(pid) { - tree[pid].forEach(function(pidpid) { - if (!killed[pidpid]) { - killPid(pidpid, signal); - killed[pidpid] = 1; - } - }); - if (!killed[pid]) { - killPid(pid, signal); - killed[pid] = 1; - } - }); - } catch (err) { - if (callback) { - return callback(err); - } else { - throw err; - } - } - if (callback) { - return callback(); - } - } - function killPid(pid, signal) { - try { - process.kill(parseInt(pid, 10), signal); - } catch (err) { - if (err.code !== "ESRCH") - throw err; - } - } - function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { - var ps = spawnChildProcessesList(parentPid); - var allData = ""; - ps.stdout.on("data", function(data) { - var data = data.toString("ascii"); - allData += data; - }); - var onClose = function(code) { - delete pidsToProcess[parentPid]; - if (code != 0) { - if (Object.keys(pidsToProcess).length == 0) { - cb(); - } - return; - } - allData.match(/\d+/g).forEach(function(pid) { - pid = parseInt(pid, 10); - tree[parentPid].push(pid); - tree[pid] = []; - pidsToProcess[pid] = 1; - buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); - }); - }; - ps.on("close", onClose); - } - } -}); - -// submission-runner/java.cts -var java_exports = {}; -__export(java_exports, { - runJava: () => runJava -}); -module.exports = __toCommonJS(java_exports); -var import_path = require("path"); -var import_child_process = require("child_process"); -var util = __toESM(require("util")); - -// submission-runner/settings.cts -var timeoutSeconds = 30; - -// submission-runner/java.cts -var kill = require_tree_kill(); -var execPromise = util.promisify(import_child_process.exec); -var runJava = async function(params) { - console.log(`- BUILD: ${params.mainFile}`); - const compileCommand = `javac -cp ${(0, import_path.join)(params.srcDir, "src")} ${params.mainFile} -d ${(0, import_path.join)(params.srcDir, "build")}`; - try { - await execPromise(compileCommand); - } catch (e) { - const buildErrorText = e?.toString() ?? "Unknown build errors."; - console.log("Build errors: " + buildErrorText); - return { - success: false, - runResult: { kind: "CompileFailed", resultKindReason: buildErrorText } - }; - } - console.log(`- RUN: ${params.mainClass}`); - const runCommand = `java -cp "${(0, import_path.join)(params.srcDir, "build")}" ${params.mainClass}`; - try { - let outputBuffer = ""; - const child = (0, import_child_process.spawn)(runCommand, { shell: true }); - child.stdout.setEncoding("utf8"); - child.stdout.on("data", (data) => { - outputBuffer += data.toString(); - params.outputCallback?.(data.toString()); - }); - child.stderr.setEncoding("utf8"); - child.stderr.on("data", (data) => { - outputBuffer += data.toString(); - params.outputCallback?.(data.toString()); - }); - const runStartTime = performance.now(); - child.stdin.write(params.input); - child.stdin.end(); - let timeLimitExceeded = false; - let completedNormally = false; - return { - success: true, - runResult: new Promise((resolve) => { - child.on("close", () => { - completedNormally = !timeLimitExceeded; - const runEndTime = performance.now(); - const runtimeMilliseconds = Math.floor(runEndTime - runStartTime); - if (completedNormally) { - clearTimeout(timeoutHandle); - resolve({ - kind: "Completed", - output: outputBuffer, - exitCode: child.exitCode, - runtimeMilliseconds - }); - } else { - console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`); - resolve({ - kind: "TimeLimitExceeded", - output: outputBuffer, - resultKindReason: `Timeout after ${timeoutSeconds} seconds` - }); - } - }); - const timeoutHandle = setTimeout(() => { - if (completedNormally) { - return; - } - console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`); - timeLimitExceeded = true; - child.stdin.end(); - child.stdin.destroy(); - child.stdout.destroy(); - child.stderr.destroy(); - child.kill("SIGKILL"); - }, timeoutSeconds * 1e3); - }), - killFunc() { - if (child.pid !== void 0) { - if (!completedNormally && !timeLimitExceeded) { - kill(child.pid); - params.outputCallback?.("\n[Manually stopped]"); - } - } - } - }; - } catch (error) { - return { success: false, runResult: { kind: "RunError" } }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - runJava -}); diff --git a/shared/dist/settings.js b/shared/dist/settings.js deleted file mode 100644 index 57ab5f0..0000000 --- a/shared/dist/settings.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// submission-runner/settings.cts -var settings_exports = {}; -__export(settings_exports, { - timeoutSeconds: () => timeoutSeconds -}); -module.exports = __toCommonJS(settings_exports); -var timeoutSeconds = 30; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - timeoutSeconds -}); diff --git a/shared/dist/types.js b/shared/dist/types.js deleted file mode 100644 index 49f6477..0000000 --- a/shared/dist/types.js +++ /dev/null @@ -1,3778 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// submission-runner/types.cts -var types_exports = {}; -__export(types_exports, { - RunResultZod: () => RunResultZod -}); -module.exports = __toCommonJS(types_exports); - -// node_modules/zod/lib/index.mjs -var util; -(function(util2) { - util2.assertEqual = (val) => val; - function assertIs(_arg) { - } - util2.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util2.assertNever = assertNever; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class extends Error { - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - get errors() { - return this.issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; -var overrideErrorMap = errorMap; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} -var makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: issueData.message || errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap - // then global default map - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - syncPairs.push({ - key: await pair.key, - value: await pair.value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil || (errorUtil = {})); -var ParseInputLazyPath = class { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - if (typeof ctx.data === "undefined") { - return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; - } - return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this, this._def); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[a-z][a-z0-9]*$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; -var 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; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; -var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -var datetimeRegex = (args) => { - if (args.precision) { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); - } - } else if (args.precision === 0) { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); - } - } else { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); - } - } -}; -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext( - ctx2, - { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - } - // - ); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - datetime(options) { - var _a; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / Math.pow(10, decCount); -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return this._cached = { shape, keys }; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") - ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - syncPairs.push({ - key, - value: await pair.value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new _ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - }); - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return Object.keys(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else { - return null; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (this._def.values.indexOf(input.data) === -1) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values) { - return _ZodEnum.create(values); - } - exclude(values) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (nativeEnumValues.indexOf(input.data) === -1) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.issues.length) { - return { - status: "dirty", - value: ctx.data - }; - } - if (ctx.common.async) { - return Promise.resolve(processed).then((processed2) => { - return this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - }); - } else { - return this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } - } - util.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - if (isValid(result)) { - result.value = Object.freeze(result.value); - } - return result; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -var custom = (check, params = {}, fatal) => { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - if (!check(data)) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); -}; -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) -}; -var NEVER = INVALID; -var z = /* @__PURE__ */ Object.freeze({ - __proto__: null, - defaultErrorMap: errorMap, - setErrorMap, - getErrorMap, - makeIssue, - EMPTY_PATH, - addIssueToContext, - ParseStatus, - INVALID, - DIRTY, - OK, - isAborted, - isDirty, - isValid, - isAsync, - get util() { - return util; - }, - get objectUtil() { - return objectUtil; - }, - ZodParsedType, - getParsedType, - ZodType, - ZodString, - ZodNumber, - ZodBigInt, - ZodBoolean, - ZodDate, - ZodSymbol, - ZodUndefined, - ZodNull, - ZodAny, - ZodUnknown, - ZodNever, - ZodVoid, - ZodArray, - ZodObject, - ZodUnion, - ZodDiscriminatedUnion, - ZodIntersection, - ZodTuple, - ZodRecord, - ZodMap, - ZodSet, - ZodFunction, - ZodLazy, - ZodLiteral, - ZodEnum, - ZodNativeEnum, - ZodPromise, - ZodEffects, - ZodTransformer: ZodEffects, - ZodOptional, - ZodNullable, - ZodDefault, - ZodCatch, - ZodNaN, - BRAND, - ZodBranded, - ZodPipeline, - ZodReadonly, - custom, - Schema: ZodType, - ZodSchema: ZodType, - late, - get ZodFirstPartyTypeKind() { - return ZodFirstPartyTypeKind; - }, - coerce, - any: anyType, - array: arrayType, - bigint: bigIntType, - boolean: booleanType, - date: dateType, - discriminatedUnion: discriminatedUnionType, - effect: effectsType, - "enum": enumType, - "function": functionType, - "instanceof": instanceOfType, - intersection: intersectionType, - lazy: lazyType, - literal: literalType, - map: mapType, - nan: nanType, - nativeEnum: nativeEnumType, - never: neverType, - "null": nullType, - nullable: nullableType, - number: numberType, - object: objectType, - oboolean, - onumber, - optional: optionalType, - ostring, - pipeline: pipelineType, - preprocess: preprocessType, - promise: promiseType, - record: recordType, - set: setType, - strictObject: strictObjectType, - string: stringType, - symbol: symbolType, - transformer: effectsType, - tuple: tupleType, - "undefined": undefinedType, - union: unionType, - unknown: unknownType, - "void": voidType, - NEVER, - ZodIssueCode, - quotelessJson, - ZodError -}); - -// submission-runner/types.cts -var RunResultKind = z.enum([ - "CompileFailed", - "TimeLimitExceeded", - "Completed", - "SandboxError", - "RunError" -]); -var RunResultZod = z.object({ - kind: RunResultKind, - output: z.string().optional(), - exitCode: z.number().optional(), - runtimeMilliseconds: z.number().optional(), - resultKindReason: z.string().optional() -}).strict(); -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - RunResultZod -}); diff --git a/shared/package.json b/shared/package.json index 01ba0ec..d298ebf 100644 --- a/shared/package.json +++ b/shared/package.json @@ -1,7 +1,7 @@ { "name": "bwcontest-shared", "scripts": { - "build": "esbuild submission-runner/*.cts --bundle --outdir=dist --format=cjs --platform=node", + "build": "esbuild submission-runner/*.cts --bundle --outdir=build --format=cjs --platform=node --sourcemap", "format": "prettier --write .", "lint": "prettier --check . && eslint .", "check": "tsc -noEmit" diff --git a/web/Dockerfile b/web/Dockerfile index a5a4816..5c166fb 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -2,9 +2,6 @@ FROM ubuntu:22.04 # Setup -RUN mkdir web -WORKDIR /app/web - RUN apt-get update RUN apt-get install curl -y @@ -14,23 +11,26 @@ RUN apt-get install nodejs git -y RUN git config --global user.name "Admin" RUN git config --global user.email noemail@example.com -# Prep Web - -COPY ./web/package*.json ./ -RUN npm install -COPY ./web/ . - # Prep Shared WORKDIR /app RUN mkdir shared WORKDIR /app/shared +COPY ./shared/package*.json ./ +RUN npm ci COPY ./shared/ . +RUN npm run build + +# Prep Web + +RUN mkdir web +WORKDIR /app/web +COPY ./web/package*.json ./ +RUN npm ci +COPY ./web/ . # Env/Build/Run -WORKDIR /app/web - ENV PORT=3000 EXPOSE 3000 EXPOSE 7006