diff --git a/db/db.json b/db/db.json index 61aba61..3578e3a 100644 --- a/db/db.json +++ b/db/db.json @@ -3,7 +3,7 @@ "HY-1": { "fullName": "Founder" }, - "MEMBER-samrussell99@pm.me": { + "MEMBER-1": { "email": "samrussell99@pm.me", "firstName": "Sam", "lastName": "Russell", @@ -317,6 +317,11 @@ "url": "https://hyperia.so/signup?token=", "uuid": "f2016b40-a179-47ec-a415-84caa7da8521", "used": false + }, + "POST-HY-1": { + "text": "This is the first message ever.", + "time": "11.24.2025-12:54:360784am", + "sentBy": "MEMBER-1" } }, "edges": {} diff --git a/main.js b/main.js index 7170bba..5f4eb8f 100644 --- a/main.js +++ b/main.js @@ -2,6 +2,8 @@ const { app, BrowserWindow, nativeImage } = require('electron'); const path = require('path'); +process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "true"; + function createWindow() { const win = new BrowserWindow({ show: false, // window is hidden diff --git a/server/auth.js b/server/auth.js index 164a18a..957d4ed 100644 --- a/server/auth.js +++ b/server/auth.js @@ -28,6 +28,21 @@ export default class AuthHandler { } } + getProfile(req, res) { + const token = req.cookies.auth_token; + if (!token) return res.status(401).send({ error: "No auth token" }); + + try { + const payload = jwt.verify(token, process.env.JWT_SECRET); + const email = payload.email; + + const user = db.members.getByEmail(email); + res.send({ email: user.email, name: user.firstName + " " + user.lastName }); + } catch (err) { + res.status(401).send({ error: "Invalid token" }); + } + } + async login(req, res) { const { email, password } = req.body; let foundUser = global.db.members.getByEmail(email) @@ -40,7 +55,8 @@ export default class AuthHandler { if (!valid) { res.status(400).json({ error: 'Incorrect password.' }); } else { - const payload = { id: foundUser.id }; + const payload = { email: foundUser.email }; + console.log(payload) const secret = process.env.JWT_SECRET; const options = { expiresIn: "2h" }; const token = jwt.sign(payload, secret, options); diff --git a/server/db/db.js b/server/db/db.js index 00798ed..bce6529 100644 --- a/server/db/db.js +++ b/server/db/db.js @@ -5,16 +5,19 @@ import QuillDB from "../_/quilldb.js" import Titles from "./model/Titles.js" import Members from './model/Members.js' import Tokens from './model/Tokens.js' +import Posts from "./model/Posts.js" export default class Database { titles = new Titles() members = new Members() tokens = new Tokens() + posts = new Posts() fromID = { "HY": this.titles, "MEMBER": this.members, - "TOKEN": this.tokens + "TOKEN": this.tokens, + "POST": this.posts } constructor() { @@ -39,7 +42,7 @@ export default class Database { try { let collection = this.fromID[type] if(collection) { - collection.save(node) + collection.save(node, id) } else { throw new Error("Type does not exist for node: ", id) } @@ -63,12 +66,14 @@ export default class Database { let arrs = [ this.titles.entries, this.members.entries, - this.tokens.entries + this.tokens.entries, + this.posts.entries ] let ids = [ Object.entries(this.titles.ids), Object.entries(this.members.ids), Object.entries(this.tokens.ids), + Object.entries(this.posts.ids), ] for(let i=0; i {return s.startsWith("$argon2")} save(member) { - let id = `MEMBER-${member.email}` + let id = `MEMBER-${this.entries.length+1}` let result = this.schema.safeParse(member) if(result.success) { try { @@ -45,29 +45,31 @@ export default class Members extends OrderedObject { newMember.tokenUsed = tokenID const hash = await argon2.hash(newMember.password); newMember.password = hash - newMember.joined = this.currentTime() + newMember.joined = global.currentTime() this.save(newMember) } - getByEmail(email) { - return super.get(`MEMBER-${email}`) + get(id) { + return this.entries[this.ids[id]] } - currentTime() { - const now = new Date(); + getByEmail(email) { + for(let i=0; i= 12 ? "pm" : "am"; - hours = hours % 12 || 12; // convert to 12-hour format - - const minutes = String(now.getMinutes()).padStart(2, "0"); - const seconds = String(now.getSeconds()).padStart(2, "0"); - const ms = String(now.getMilliseconds()).padStart(4, "0"); // 4-digit like "5838" - - return `${month}.${day}.${year}-${hours}:${minutes}:${seconds}${ms}${ampm}`; + getIDFromEmail(email) { + let index = 0 + for(let i=0; i { + console.log("saving db") + global.db.saveData() + }, 5000) + const server = http.createServer(app); - initWebSocket(server); + global.Socket = new Socket(server); const PORT = 3003; server.listen(PORT, () => { console.logclean("\n") @@ -219,11 +225,4 @@ console.logclean = function (...args) { // _log.call(console, `[${location}]`, ...args); // }; -global.ServerError = class extends Error { - constructor(status, msg) { - super(msg); - this.status = status; - } -} - const server = new Server() \ No newline at end of file diff --git a/server/util.js b/server/util.js new file mode 100644 index 0000000..7ae1f68 --- /dev/null +++ b/server/util.js @@ -0,0 +1,24 @@ +global.ServerError = class extends Error { + constructor(status, msg) { + super(msg); + this.status = status; + } +} + +global.currentTime = function () { + const now = new Date(); + + const month = String(now.getMonth() + 1).padStart(2, "0"); + const day = String(now.getDate()).padStart(2, "0"); + const year = now.getFullYear(); + + let hours = now.getHours(); + const ampm = hours >= 12 ? "pm" : "am"; + hours = hours % 12 || 12; // convert to 12-hour format + + const minutes = String(now.getMinutes()).padStart(2, "0"); + const seconds = String(now.getSeconds()).padStart(2, "0"); + const ms = String(now.getMilliseconds()).padStart(4, "0"); // 4-digit like "5838" + + return `${month}.${day}.${year}-${hours}:${minutes}:${seconds}${ms}${ampm}`; +} \ No newline at end of file diff --git a/server/ws.js b/server/ws.js deleted file mode 100644 index 8dd88e9..0000000 --- a/server/ws.js +++ /dev/null @@ -1,31 +0,0 @@ -const { WebSocket, WebSocketServer } = require('ws'); - -let wss; - -export function initWebSocket(server) { - wss = new WebSocketServer({ server }); - - wss.on('connection', (ws, req) => { - console.log('✅ New WebSocket client connected'); - - ws.on('close', () => { - console.log('Client disconnected'); - }); - }); - - console.log('WebSocket server initialized'); -} - -// Broadcast a message to all connected clients -export function broadcast(reqType, data) { - if (!wss) return; - - const payload = typeof data === 'string' ? data : JSON.stringify(data); - const message = `${reqType}|${payload}`; - - wss.clients.forEach(client => { - if (client.readyState === WebSocket.OPEN) { - client.send(message); - } - }); -} diff --git a/server/ws/handlers/ForumHandler.js b/server/ws/handlers/ForumHandler.js new file mode 100644 index 0000000..b35f273 --- /dev/null +++ b/server/ws/handlers/ForumHandler.js @@ -0,0 +1,43 @@ +const { z } = require("zod") + +const sendSchema = z.object({ + forum: z.string(), + text: z.string(), +}) +.strict() + +const getSchema = z.object({ + forum: z.string(), + number: z.number() +}) +.strict() + + +export default class ForumHandler { + static handleSend(msg, ws) { + try { + global.db.posts.add(msg.text, msg.forum, ws.userEmail) + global.Socket.broadcast({event: "new-message", app: "FORUM", forum: msg.forum, msg: this.handleGet({forum: msg.forum, number: 100})}) + return {success: true} + } catch(e) { + console.error(e) + } + } + + static handleGet(msg) { + let data = global.db.posts.get(msg.forum, msg.number) + return data + } + + static handle(operation, msg, ws) { + switch(operation) { + case "SEND": + if(!sendSchema.safeParse(msg).success) throw new Error("Incorrectly formatted Forum ws message!") + return this.handleSend(msg, ws) + case "GET": + if(!getSchema.safeParse(msg).success) throw new Error("Incorrectly formatted Forum ws message!") + return this.handleGet(msg) + } + + } +} \ No newline at end of file diff --git a/server/ws/ws.js b/server/ws/ws.js new file mode 100644 index 0000000..91db7b5 --- /dev/null +++ b/server/ws/ws.js @@ -0,0 +1,93 @@ +const { WebSocket, WebSocketServer } = require('ws'); +const { z } = require("zod") +const jwt = require('jsonwebtoken'); +import ForumHandler from "./handlers/ForumHandler.js" + +export default class Socket { + wss; + messageSchema = z.object({ + id: z.string(), + app: z.string(), + operation: z.string().optional(), + msg: z.union([ + z.object({}).passthrough(), // allows any object + z.array(z.any()) // allows any array + ]) + }).strict() + + constructor(server) { + this.wss = new WebSocketServer({ server }); + + this.wss.on('connection', (ws, req) => { + console.log('✅ New WebSocket client connected'); + + function parseCookies(cookieHeader = "") { + return Object.fromEntries( + cookieHeader.split(";").map(c => { + const [key, ...v] = c.trim().split("="); + return [key, decodeURIComponent(v.join("="))]; + }) + ); + } + + const cookies = parseCookies(req.headers.cookie); + const token = cookies.auth_token; + if (!token) throw new Error("No auth token"); + const payload = jwt.verify(token, process.env.JWT_SECRET); + ws.userEmail = payload.email; + + ws.on('message', (msg) => { + this.handleMessage(msg, ws); + }); + + ws.on('close', () => { + console.log('Client disconnected'); + }); + }); + + console.log('WebSocket server initialized'); + } + + // Build a system where the ws obj is updated every time on navigate, so it already has context + // this way, we can only send broadcast messages to clients that actually have that app / subapp open + handleMessage = (msg, ws) => { + try { + const text = msg.toString(); + const req = JSON.parse(text); + if(!this.messageSchema.safeParse(req).success) throw new Error("Socket.handleMessage: Incorrectly formatted incoming ws message!") + + let responseData; + switch (req.app) { + case "FORUM": + responseData = ForumHandler.handle(req.operation, req.msg, ws) + break; + + default: + console.error("unknown ws message") + } + + let response = { + ...req + } + response.msg = responseData + + if(!this.messageSchema.safeParse(response).success) throw new Error("Socket.handleMessage: Incorrectly formatted outgoing ws message!") + ws.send(JSON.stringify(response)) + + } catch (e) { + console.error("Invalid WS message:", e); + } + } + + broadcast(event) { + if (!this.wss) return; + + let message = JSON.stringify(event) + + this.wss.clients.forEach(ws => { + if (ws.readyState === WebSocket.OPEN) { + ws.send(message); + } + }); + } +} diff --git a/ui/_/code/quill.js b/ui/_/code/quill.js index 618ec01..48a6225 100644 --- a/ui/_/code/quill.js +++ b/ui/_/code/quill.js @@ -1,6 +1,7 @@ /* Sam Russell Captured Sun + 11.24.25 - Fixing onClick because it was reversed, adding event to onHover params 11.23.25 - Added onSubmit() event for form submission, added marginHorizontal() and marginVertical() 11.20.25 - Added "pct" style unit, added alignVertical and alignHorizontal for flex boxes 11.19.25 - Allowing for "auto" values in otherwise numeric styles, adding vmin and vmax units @@ -496,7 +497,6 @@ HTMLElement.prototype.alignVertical = function (value) { } if (direction === "column" || direction === "column-reverse") { - console.log("using justify") this.style.justifyContent = value; } else { this.style.alignItems = value; @@ -824,8 +824,8 @@ HTMLElement.prototype.onAppear = function(func) { }; HTMLElement.prototype.onClick = function(func) { - const onMouseDown = () => func.call(this, true); - const onMouseUp = () => func.call(this, false); + const onMouseDown = () => func.call(this, false); + const onMouseUp = () => func.call(this, true); this._storeListener("mousedown", onMouseDown); this._storeListener("mouseup", onMouseUp); return this; @@ -847,8 +847,8 @@ HTMLElement.prototype.onRightClick = function(func) { }; HTMLElement.prototype.onHover = function(cb) { - const onEnter = () => cb.call(this, true); - const onLeave = () => cb.call(this, false); + const onEnter = (e) => cb.call(this, true, e); + const onLeave = (e) => cb.call(this, false, e); this._storeListener("mouseover", onEnter); this._storeListener("mouseleave", onLeave); return this; diff --git a/ui/_/code/zod.js b/ui/_/code/zod.js new file mode 100644 index 0000000..a4e9e54 --- /dev/null +++ b/ui/_/code/zod.js @@ -0,0 +1,8 @@ +/** + * Minified by jsDelivr using Terser v5.39.0. + * Original file: /npm/zod@3.24.4/lib/index.umd.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Zod={})}(this,(function(e){"use strict";var t;e.util=void 0,(t=e.util||(e.util={})).assertEqual=e=>e,t.assertIs=function(e){},t.assertNever=function(e){throw new Error},t.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},t.getValidEnumValues=e=>{const a=t.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const t of a)s[t]=e[t];return t.objectValues(s)},t.objectValues=e=>t.objectKeys(e).map((function(t){return e[t]})),t.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},t.find=(e,t)=>{for(const a of e)if(t(a))return a},t.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,t.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},t.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,e.objectUtil=void 0,(e.objectUtil||(e.objectUtil={})).mergeShapes=(e,t)=>({...e,...t});const a=e.util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),s=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},r=e.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"]),n=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class i extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},a={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(s);else if("invalid_return_type"===r.code)s(r.returnTypeError);else if("invalid_arguments"===r.code)s(r.argumentsError);else if(0===r.path.length)a._errors.push(t(r));else{let e=a,s=0;for(;se.message){const t={},a=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}}i.create=e=>new i(e);const o=(t,s)=>{let n;switch(t.code){case r.invalid_type:n=t.received===a.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case r.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,e.util.jsonStringifyReplacer)}`;break;case r.unrecognized_keys:n=`Unrecognized key(s) in object: ${e.util.joinValues(t.keys,", ")}`;break;case r.invalid_union:n="Invalid input";break;case r.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${e.util.joinValues(t.options)}`;break;case r.invalid_enum_value:n=`Invalid enum value. Expected ${e.util.joinValues(t.options)}, received '${t.received}'`;break;case r.invalid_arguments:n="Invalid function arguments";break;case r.invalid_return_type:n="Invalid function return type";break;case r.invalid_date:n="Invalid date";break;case r.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:e.util.assertNever(t.validation):n="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case r.too_small:n="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case r.too_big:n="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case r.custom:n="Invalid input";break;case r.invalid_intersection_types:n="Intersection results could not be merged";break;case r.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case r.not_finite:n="Number must be finite";break;default:n=s.defaultError,e.util.assertNever(t)}return{message:n}};let d=o;function u(e){d=e}function c(){return d}const l=e=>{const{data:t,path:a,errorMaps:s,issueData:r}=e,n=[...a,...r.path||[]],i={...r,path:n};if(void 0!==r.message)return{...r,path:n,message:r.message};let o="";const d=s.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(i,{data:t,defaultError:o}).message;return{...r,path:n,message:o}},p=[];function h(e,t){const a=c(),s=l({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===o?void 0:o].filter((e=>!!e))});e.common.issues.push(s)}class m{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return f;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){const a=[];for(const e of t){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return m.mergeObjectSync(e,a)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:r}=s;if("aborted"===t.status)return f;if("aborted"===r.status)return f;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!s.alwaysSet||(a[t.value]=r.value)}return{status:e.value,value:a}}}const f=Object.freeze({status:"aborted"}),y=e=>({status:"dirty",value:e}),v=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,g=e=>"dirty"===e.status,b=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;function x(e,t,a,s){if("a"===a&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===a?s:"a"===a?s.call(e):s?s.value:t.get(e)}function Z(e,t,a,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,a):r?r.value=a:t.set(e,a),a}var w,T,P;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(w||(w={}));class O{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const C=(e,t)=>{if(b(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new i(e.common.issues);return this._error=t,this._error}}};function N(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:r}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{var n,i;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:r.defaultError}:void 0===r.data?{message:null!==(n=null!=o?o:s)&&void 0!==n?n:r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:null!==(i=null!=o?o:a)&&void 0!==i?i:r.defaultError}},description:r}}class A{get description(){return this._def.description}_getType(e){return s(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new m,ctx:{common:e.parent.common,data:e.data,parsedType:s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){var a;const r={common:{issues:[],async:null!==(a=null==t?void 0:t.async)&&void 0!==a&&a,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)},n=this._parseSync({data:e,path:r.path,parent:r});return C(r,n)}"~validate"(e){var t,a;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:r});return b(t)?{value:t.value}:{issues:r.common.issues}}catch(e){(null===(a=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===a?void 0:a.includes("encountered"))&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then((e=>b(e)?{value:e.value}:{issues:r.common.issues}))}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)},r=this._parse({data:e,path:a.path,parent:a}),n=await(k(r)?r:Promise.resolve(r));return C(a,n)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),i=()=>s.addIssue({code:r.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1)))}_refinement(t){return new Ae({schema:this,typeName:e.ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Se.create(this,this._def)}nullable(){return je.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return Ne.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return _e.create(this,e,this._def)}transform(t){return new Ae({...N(this._def),schema:this,typeName:e.ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const a="function"==typeof t?t:()=>t;return new Ee({...N(this._def),innerType:this,defaultValue:a,typeName:e.ZodFirstPartyTypeKind.ZodDefault})}brand(){return new Ke({typeName:e.ZodFirstPartyTypeKind.ZodBranded,type:this,...N(this._def)})}catch(t){const a="function"==typeof t?t:()=>t;return new Fe({...N(this._def),innerType:this,catchValue:a,typeName:e.ZodFirstPartyTypeKind.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return $e.create(this,e)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const S=/^c[^\s-]{8,}$/i,j=/^[0-9a-z]+$/,E=/^[0-9A-HJKMNP-TV-Z]{26}$/i,F=/^[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,I=/^[a-z0-9_-]{21}$/i,R=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,K=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let M;const D=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,L=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,z=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,V=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,B=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,W="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",q=new RegExp(`^${W}$`);function J(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Y(e){let t=`${W}T${J(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function H(e,t){if(!R.test(e))return!1;try{const[a]=e.split("."),s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),r=JSON.parse(atob(s));return"object"==typeof r&&null!==r&&(!(!r.typ||!r.alg)&&(!t||r.alg===t))}catch(e){return!1}}function G(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!V.test(e))}class X extends A{_parse(t){this._def.coerce&&(t.data=String(t.data));if(this._getType(t)!==a.string){const e=this._getOrReturnCtx(t);return h(e,{code:r.invalid_type,expected:a.string,received:e.parsedType}),f}const s=new m;let n;for(const a of this._def.checks)if("min"===a.kind)t.data.lengtha.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:r.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if("length"===a.kind){const e=t.data.length>a.value,i=t.data.lengthe.test(t)),{validation:t,code:r.invalid_string,...w.errToObj(a)})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...w.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...w.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...w.errToObj(e)})}datetime(e){var t,a;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(a=null==e?void 0:e.local)&&void 0!==a&&a,...w.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...w.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...w.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...w.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...w.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...w.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...w.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...w.errToObj(t)})}nonempty(e){return this.min(1,w.errToObj(e))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.values?a:s;return parseInt(e.toFixed(r).replace(".",""))%parseInt(t.toFixed(r).replace(".",""))/Math.pow(10,r)}X.create=t=>{var a;return new X({checks:[],typeName:e.ZodFirstPartyTypeKind.ZodString,coerce:null!==(a=null==t?void 0:t.coerce)&&void 0!==a&&a,...N(t)})};class ee extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){this._def.coerce&&(t.data=Number(t.data));if(this._getType(t)!==a.number){const e=this._getOrReturnCtx(t);return h(e,{code:r.invalid_type,expected:a.number,received:e.parsedType}),f}let s;const n=new m;for(const a of this._def.checks)if("int"===a.kind)e.util.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{code:r.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty());else if("min"===a.kind){(a.inclusive?t.dataa.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),h(s,{code:r.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty())}else"multipleOf"===a.kind?0!==Q(t.data,a.value)&&(s=this._getOrReturnCtx(t,s),h(s,{code:r.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):"finite"===a.kind?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{code:r.not_finite,message:a.message}),n.dirty()):e.util.assertNever(a);return{status:n.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,a,s){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:w.toString(s)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===t.kind||"multipleOf"===t.kind&&e.util.isInteger(t.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.valuenew ee({checks:[],typeName:e.ZodFirstPartyTypeKind.ZodNumber,coerce:(null==t?void 0:t.coerce)||!1,...N(t)});class te extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch(e){return this._getInvalidInput(t)}if(this._getType(t)!==a.bigint)return this._getInvalidInput(t);let s;const n=new m;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?t.dataa.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),h(s,{code:r.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty())}else"multipleOf"===a.kind?t.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),h(s,{code:r.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):e.util.assertNever(a);return{status:n.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,a,s){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:w.toString(s)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value{var a;return new te({checks:[],typeName:e.ZodFirstPartyTypeKind.ZodBigInt,coerce:null!==(a=null==t?void 0:t.coerce)&&void 0!==a&&a,...N(t)})};class ae extends A{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.boolean,received:t.parsedType}),f}return v(e.data)}}ae.create=t=>new ae({typeName:e.ZodFirstPartyTypeKind.ZodBoolean,coerce:(null==t?void 0:t.coerce)||!1,...N(t)});class se extends A{_parse(t){this._def.coerce&&(t.data=new Date(t.data));if(this._getType(t)!==a.date){const e=this._getOrReturnCtx(t);return h(e,{code:r.invalid_type,expected:a.date,received:e.parsedType}),f}if(isNaN(t.data.getTime())){return h(this._getOrReturnCtx(t),{code:r.invalid_date}),f}const s=new m;let n;for(const a of this._def.checks)"min"===a.kind?t.data.getTime()a.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:r.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):e.util.assertNever(a);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(e){return new se({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:w.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew se({checks:[],coerce:(null==t?void 0:t.coerce)||!1,typeName:e.ZodFirstPartyTypeKind.ZodDate,...N(t)});class re extends A{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.symbol,received:t.parsedType}),f}return v(e.data)}}re.create=t=>new re({typeName:e.ZodFirstPartyTypeKind.ZodSymbol,...N(t)});class ne extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.undefined,received:t.parsedType}),f}return v(e.data)}}ne.create=t=>new ne({typeName:e.ZodFirstPartyTypeKind.ZodUndefined,...N(t)});class ie extends A{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.null,received:t.parsedType}),f}return v(e.data)}}ie.create=t=>new ie({typeName:e.ZodFirstPartyTypeKind.ZodNull,...N(t)});class oe extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return v(e.data)}}oe.create=t=>new oe({typeName:e.ZodFirstPartyTypeKind.ZodAny,...N(t)});class de extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return v(e.data)}}de.create=t=>new de({typeName:e.ZodFirstPartyTypeKind.ZodUnknown,...N(t)});class ue extends A{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.never,received:t.parsedType}),f}}ue.create=t=>new ue({typeName:e.ZodFirstPartyTypeKind.ZodNever,...N(t)});class ce extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.void,received:t.parsedType}),f}return v(e.data)}}ce.create=t=>new ce({typeName:e.ZodFirstPartyTypeKind.ZodVoid,...N(t)});class le extends A{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==a.array)return h(t,{code:r.invalid_type,expected:a.array,received:t.parsedType}),f;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.lengthn.maxLength.value&&(h(t,{code:r.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>n.type._parseAsync(new O(t,e,t.path,a))))).then((e=>m.mergeArray(s,e)));const i=[...t.data].map(((e,a)=>n.type._parseSync(new O(t,e,t.path,a))));return m.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new le({...this._def,minLength:{value:e,message:w.toString(t)}})}max(e,t){return new le({...this._def,maxLength:{value:e,message:w.toString(t)}})}length(e,t){return new le({...this._def,exactLength:{value:e,message:w.toString(t)}})}nonempty(e){return this.min(1,e)}}function pe(e){if(e instanceof he){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=Se.create(pe(s))}return new he({...e._def,shape:()=>t})}return e instanceof le?new le({...e._def,type:pe(e.element)}):e instanceof Se?Se.create(pe(e.unwrap())):e instanceof je?je.create(pe(e.unwrap())):e instanceof ge?ge.create(e.items.map((e=>pe(e)))):e}le.create=(t,a)=>new le({type:t,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodFirstPartyTypeKind.ZodArray,...N(a)});class he extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),a=e.util.objectKeys(t);return this._cached={shape:t,keys:a}}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.object,received:t.parsedType}),f}const{status:t,ctx:s}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ue&&"strip"===this._def.unknownKeys))for(const e in s.data)i.includes(e)||o.push(e);const d=[];for(const e of i){const t=n[e],a=s.data[e];d.push({key:{status:"valid",value:e},value:t._parse(new O(s,a,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ue){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)d.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)o.length>0&&(h(s,{code:r.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=s.data[t];d.push({key:{status:"valid",value:t},value:e._parse(new O(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of d){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>m.mergeObjectSync(t,e))):m.mergeObjectSync(t,d)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new he({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,a)=>{var s,r,n,i;const o=null!==(n=null===(r=(s=this._def).errorMap)||void 0===r?void 0:r.call(s,t,a).message)&&void 0!==n?n:a.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=w.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new he({...this._def,unknownKeys:"strip"})}passthrough(){return new he({...this._def,unknownKeys:"passthrough"})}extend(e){return new he({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(t){return new he({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:e.ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new he({...this._def,catchall:e})}pick(t){const a={};return e.util.objectKeys(t).forEach((e=>{t[e]&&this.shape[e]&&(a[e]=this.shape[e])})),new he({...this._def,shape:()=>a})}omit(t){const a={};return e.util.objectKeys(this.shape).forEach((e=>{t[e]||(a[e]=this.shape[e])})),new he({...this._def,shape:()=>a})}deepPartial(){return pe(this)}partial(t){const a={};return e.util.objectKeys(this.shape).forEach((e=>{const s=this.shape[e];t&&!t[e]?a[e]=s:a[e]=s.optional()})),new he({...this._def,shape:()=>a})}required(t){const a={};return e.util.objectKeys(this.shape).forEach((e=>{if(t&&!t[e])a[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Se;)t=t._def.innerType;a[e]=t}})),new he({...this._def,shape:()=>a})}keyof(){return Pe(e.util.objectKeys(this.shape))}}he.create=(t,a)=>new he({shape:()=>t,unknownKeys:"strip",catchall:ue.create(),typeName:e.ZodFirstPartyTypeKind.ZodObject,...N(a)}),he.strictCreate=(t,a)=>new he({shape:()=>t,unknownKeys:"strict",catchall:ue.create(),typeName:e.ZodFirstPartyTypeKind.ZodObject,...N(a)}),he.lazycreate=(t,a)=>new he({shape:t,unknownKeys:"strip",catchall:ue.create(),typeName:e.ZodFirstPartyTypeKind.ZodObject,...N(a)});class me extends A{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new i(e.ctx.common.issues)));return h(t,{code:r.invalid_union,unionErrors:a}),f}));{let e;const s=[];for(const r of a){const a={...t,common:{...t.common,issues:[]},parent:null},n=r._parseSync({data:t.data,path:t.path,parent:a});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new i(e)));return h(t,{code:r.invalid_union,unionErrors:n}),f}}get options(){return this._def.options}}me.create=(t,a)=>new me({options:t,typeName:e.ZodFirstPartyTypeKind.ZodUnion,...N(a)});const fe=t=>t instanceof we?fe(t.schema):t instanceof Ae?fe(t.innerType()):t instanceof Te?[t.value]:t instanceof Oe?t.options:t instanceof Ce?e.util.objectValues(t.enum):t instanceof Ee?fe(t._def.innerType):t instanceof ne?[void 0]:t instanceof ie?[null]:t instanceof Se?[void 0,...fe(t.unwrap())]:t instanceof je?[null,...fe(t.unwrap())]:t instanceof Ke||t instanceof Me?fe(t.unwrap()):t instanceof Fe?fe(t._def.innerType):[];class ye extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return h(t,{code:r.invalid_type,expected:a.object,received:t.parsedType}),f;const s=this.discriminator,n=t.data[s],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:r.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,a,s){const r=new Map;for(const e of a){const a=fe(e.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const s of a){if(r.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);r.set(s,e)}}return new ye({typeName:e.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:a,optionsMap:r,...N(s)})}}function ve(t,r){const n=s(t),i=s(r);if(t===r)return{valid:!0,data:t};if(n===a.object&&i===a.object){const a=e.util.objectKeys(r),s=e.util.objectKeys(t).filter((e=>-1!==a.indexOf(e))),n={...t,...r};for(const e of s){const a=ve(t[e],r[e]);if(!a.valid)return{valid:!1};n[e]=a.data}return{valid:!0,data:n}}if(n===a.array&&i===a.array){if(t.length!==r.length)return{valid:!1};const e=[];for(let a=0;a{if(_(e)||_(s))return f;const n=ve(e.value,s.value);return n.valid?((g(e)||g(s))&&t.dirty(),{status:t.value,value:n.data}):(h(a,{code:r.invalid_intersection_types}),f)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}_e.create=(t,a,s)=>new _e({left:t,right:a,typeName:e.ZodFirstPartyTypeKind.ZodIntersection,...N(s)});class ge extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.array)return h(s,{code:r.invalid_type,expected:a.array,received:s.parsedType}),f;if(s.data.lengththis._def.items.length&&(h(s,{code:r.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new O(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(n).then((e=>m.mergeArray(t,e))):m.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ge({...this._def,rest:e})}}ge.create=(t,a)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ge({items:t,typeName:e.ZodFirstPartyTypeKind.ZodTuple,rest:null,...N(a)})};class be extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.object)return h(s,{code:r.invalid_type,expected:a.object,received:s.parsedType}),f;const n=[],i=this._def.keyType,o=this._def.valueType;for(const e in s.data)n.push({key:i._parse(new O(s,e,s.path,e)),value:o._parse(new O(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?m.mergeObjectAsync(t,n):m.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(t,a,s){return new be(a instanceof A?{keyType:t,valueType:a,typeName:e.ZodFirstPartyTypeKind.ZodRecord,...N(s)}:{keyType:X.create(),valueType:t,typeName:e.ZodFirstPartyTypeKind.ZodRecord,...N(a)})}}class ke extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.map)return h(s,{code:r.invalid_type,expected:a.map,received:s.parsedType}),f;const n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map((([e,t],a)=>({key:n._parse(new O(s,e,s.path,[a,"key"])),value:i._parse(new O(s,t,s.path,[a,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of o){const s=await a.key,r=await a.value;if("aborted"===s.status||"aborted"===r.status)return f;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of o){const s=a.key,r=a.value;if("aborted"===s.status||"aborted"===r.status)return f;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}}}ke.create=(t,a,s)=>new ke({valueType:a,keyType:t,typeName:e.ZodFirstPartyTypeKind.ZodMap,...N(s)});class xe extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.set)return h(s,{code:r.invalid_type,expected:a.set,received:s.parsedType}),f;const n=this._def;null!==n.minSize&&s.data.sizen.maxSize.value&&(h(s,{code:r.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const a=new Set;for(const s of e){if("aborted"===s.status)return f;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const d=[...s.data.values()].map(((e,t)=>i._parse(new O(s,e,s.path,t))));return s.common.async?Promise.all(d).then((e=>o(e))):o(d)}min(e,t){return new xe({...this._def,minSize:{value:e,message:w.toString(t)}})}max(e,t){return new xe({...this._def,maxSize:{value:e,message:w.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}xe.create=(t,a)=>new xe({valueType:t,minSize:null,maxSize:null,typeName:e.ZodFirstPartyTypeKind.ZodSet,...N(a)});class Ze extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.function)return h(t,{code:r.invalid_type,expected:a.function,received:t.parsedType}),f;function s(e,a){return l({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,c(),o].filter((e=>!!e)),issueData:{code:r.invalid_arguments,argumentsError:a}})}function n(e,a){return l({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,c(),o].filter((e=>!!e)),issueData:{code:r.invalid_return_type,returnTypeError:a}})}const d={errorMap:t.common.contextualErrorMap},u=t.data;if(this._def.returns instanceof Ne){const e=this;return v((async function(...t){const a=new i([]),r=await e._def.args.parseAsync(t,d).catch((e=>{throw a.addIssue(s(t,e)),a})),o=await Reflect.apply(u,this,r);return await e._def.returns._def.type.parseAsync(o,d).catch((e=>{throw a.addIssue(n(o,e)),a}))}))}{const e=this;return v((function(...t){const a=e._def.args.safeParse(t,d);if(!a.success)throw new i([s(t,a.error)]);const r=Reflect.apply(u,this,a.data),o=e._def.returns.safeParse(r,d);if(!o.success)throw new i([n(r,o.error)]);return o.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ze({...this._def,args:ge.create(e).rest(de.create())})}returns(e){return new Ze({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,a,s){return new Ze({args:t||ge.create([]).rest(de.create()),returns:a||de.create(),typeName:e.ZodFirstPartyTypeKind.ZodFunction,...N(s)})}}class we extends A{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}we.create=(t,a)=>new we({getter:t,typeName:e.ZodFirstPartyTypeKind.ZodLazy,...N(a)});class Te extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:r.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Pe(t,a){return new Oe({values:t,typeName:e.ZodFirstPartyTypeKind.ZodEnum,...N(a)})}Te.create=(t,a)=>new Te({value:t,typeName:e.ZodFirstPartyTypeKind.ZodLiteral,...N(a)});class Oe extends A{constructor(){super(...arguments),T.set(this,void 0)}_parse(t){if("string"!=typeof t.data){const a=this._getOrReturnCtx(t),s=this._def.values;return h(a,{expected:e.util.joinValues(s),received:a.parsedType,code:r.invalid_type}),f}if(x(this,T,"f")||Z(this,T,new Set(this._def.values),"f"),!x(this,T,"f").has(t.data)){const e=this._getOrReturnCtx(t),a=this._def.values;return h(e,{received:e.data,code:r.invalid_enum_value,options:a}),f}return v(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Oe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Oe.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}T=new WeakMap,Oe.create=Pe;class Ce extends A{constructor(){super(...arguments),P.set(this,void 0)}_parse(t){const s=e.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==a.string&&n.parsedType!==a.number){const t=e.util.objectValues(s);return h(n,{expected:e.util.joinValues(t),received:n.parsedType,code:r.invalid_type}),f}if(x(this,P,"f")||Z(this,P,new Set(e.util.getValidEnumValues(this._def.values)),"f"),!x(this,P,"f").has(t.data)){const t=e.util.objectValues(s);return h(n,{received:n.data,code:r.invalid_enum_value,options:t}),f}return v(t.data)}get enum(){return this._def.values}}P=new WeakMap,Ce.create=(t,a)=>new Ce({values:t,typeName:e.ZodFirstPartyTypeKind.ZodNativeEnum,...N(a)});class Ne extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return h(t,{code:r.invalid_type,expected:a.promise,received:t.parsedType}),f;const s=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return v(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Ne.create=(t,a)=>new Ne({type:t,typeName:e.ZodFirstPartyTypeKind.ZodPromise,...N(a)});class Ae extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:a,ctx:s}=this._processInputParams(t),r=this._def.effect||null,n={addIssue:e=>{h(s,e),e.fatal?a.abort():a.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===r.type){const e=r.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===a.value)return f;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?f:"dirty"===t.status||"dirty"===a.value?y(t.value):t}));{if("aborted"===a.value)return f;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?f:"dirty"===t.status||"dirty"===a.value?y(t.value):t}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,n);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?f:("dirty"===t.status&&a.dirty(),e(t.value),{status:a.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((t=>"aborted"===t.status?f:("dirty"===t.status&&a.dirty(),e(t.value).then((()=>({status:a.value,value:t.value}))))))}if("transform"===r.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!b(e))return e;const t=r.transform(e.value,n);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>b(e)?Promise.resolve(r.transform(e.value,n)).then((e=>({status:a.value,value:e}))):e))}e.util.assertNever(r)}}Ae.create=(t,a,s)=>new Ae({schema:t,typeName:e.ZodFirstPartyTypeKind.ZodEffects,effect:a,...N(s)}),Ae.createWithPreprocess=(t,a,s)=>new Ae({schema:a,effect:{type:"preprocess",transform:t},typeName:e.ZodFirstPartyTypeKind.ZodEffects,...N(s)});class Se extends A{_parse(e){return this._getType(e)===a.undefined?v(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Se.create=(t,a)=>new Se({innerType:t,typeName:e.ZodFirstPartyTypeKind.ZodOptional,...N(a)});class je extends A{_parse(e){return this._getType(e)===a.null?v(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}je.create=(t,a)=>new je({innerType:t,typeName:e.ZodFirstPartyTypeKind.ZodNullable,...N(a)});class Ee extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===a.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ee.create=(t,a)=>new Ee({innerType:t,typeName:e.ZodFirstPartyTypeKind.ZodDefault,defaultValue:"function"==typeof a.default?a.default:()=>a.default,...N(a)});class Fe extends A{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return k(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new i(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new i(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}Fe.create=(t,a)=>new Fe({innerType:t,typeName:e.ZodFirstPartyTypeKind.ZodCatch,catchValue:"function"==typeof a.catch?a.catch:()=>a.catch,...N(a)});class Ie extends A{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return h(t,{code:r.invalid_type,expected:a.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}Ie.create=t=>new Ie({typeName:e.ZodFirstPartyTypeKind.ZodNaN,...N(t)});const Re=Symbol("zod_brand");class Ke extends A{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}}class $e extends A{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),y(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(t,a){return new $e({in:t,out:a,typeName:e.ZodFirstPartyTypeKind.ZodPipeline})}}class Me extends A{_parse(e){const t=this._def.innerType._parse(e),a=e=>(b(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then((e=>a(e))):a(t)}unwrap(){return this._def.innerType}}function De(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function Le(e,t={},a){return e?oe.create().superRefine(((s,r)=>{var n,i;const o=e(s);if(o instanceof Promise)return o.then((e=>{var n,i;if(!e){const e=De(t,s),o=null===(i=null!==(n=e.fatal)&&void 0!==n?n:a)||void 0===i||i;r.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=De(t,s),o=null===(i=null!==(n=e.fatal)&&void 0!==n?n:a)||void 0===i||i;r.addIssue({code:"custom",...e,fatal:o})}})):oe.create()}Me.create=(t,a)=>new Me({innerType:t,typeName:e.ZodFirstPartyTypeKind.ZodReadonly,...N(a)});const ze={object:he.lazycreate};var Ve;e.ZodFirstPartyTypeKind=void 0,(Ve=e.ZodFirstPartyTypeKind||(e.ZodFirstPartyTypeKind={})).ZodString="ZodString",Ve.ZodNumber="ZodNumber",Ve.ZodNaN="ZodNaN",Ve.ZodBigInt="ZodBigInt",Ve.ZodBoolean="ZodBoolean",Ve.ZodDate="ZodDate",Ve.ZodSymbol="ZodSymbol",Ve.ZodUndefined="ZodUndefined",Ve.ZodNull="ZodNull",Ve.ZodAny="ZodAny",Ve.ZodUnknown="ZodUnknown",Ve.ZodNever="ZodNever",Ve.ZodVoid="ZodVoid",Ve.ZodArray="ZodArray",Ve.ZodObject="ZodObject",Ve.ZodUnion="ZodUnion",Ve.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ve.ZodIntersection="ZodIntersection",Ve.ZodTuple="ZodTuple",Ve.ZodRecord="ZodRecord",Ve.ZodMap="ZodMap",Ve.ZodSet="ZodSet",Ve.ZodFunction="ZodFunction",Ve.ZodLazy="ZodLazy",Ve.ZodLiteral="ZodLiteral",Ve.ZodEnum="ZodEnum",Ve.ZodEffects="ZodEffects",Ve.ZodNativeEnum="ZodNativeEnum",Ve.ZodOptional="ZodOptional",Ve.ZodNullable="ZodNullable",Ve.ZodDefault="ZodDefault",Ve.ZodCatch="ZodCatch",Ve.ZodPromise="ZodPromise",Ve.ZodBranded="ZodBranded",Ve.ZodPipeline="ZodPipeline",Ve.ZodReadonly="ZodReadonly";const Ue=(e,t={message:`Input not instance of ${e.name}`})=>Le((t=>t instanceof e),t),Be=X.create,We=ee.create,qe=Ie.create,Je=te.create,Ye=ae.create,He=se.create,Ge=re.create,Xe=ne.create,Qe=ie.create,et=oe.create,tt=de.create,at=ue.create,st=ce.create,rt=le.create,nt=he.create,it=he.strictCreate,ot=me.create,dt=ye.create,ut=_e.create,ct=ge.create,lt=be.create,pt=ke.create,ht=xe.create,mt=Ze.create,ft=we.create,yt=Te.create,vt=Oe.create,_t=Ce.create,gt=Ne.create,bt=Ae.create,kt=Se.create,xt=je.create,Zt=Ae.createWithPreprocess,wt=$e.create,Tt=()=>Be().optional(),Pt=()=>We().optional(),Ot=()=>Ye().optional(),Ct={string:e=>X.create({...e,coerce:!0}),number:e=>ee.create({...e,coerce:!0}),boolean:e=>ae.create({...e,coerce:!0}),bigint:e=>te.create({...e,coerce:!0}),date:e=>se.create({...e,coerce:!0})},Nt=f;var At=Object.freeze({__proto__:null,defaultErrorMap:o,setErrorMap:u,getErrorMap:c,makeIssue:l,EMPTY_PATH:p,addIssueToContext:h,ParseStatus:m,INVALID:f,DIRTY:y,OK:v,isAborted:_,isDirty:g,isValid:b,isAsync:k,get util(){return e.util},get objectUtil(){return e.objectUtil},ZodParsedType:a,getParsedType:s,ZodType:A,datetimeRegex:Y,ZodString:X,ZodNumber:ee,ZodBigInt:te,ZodBoolean:ae,ZodDate:se,ZodSymbol:re,ZodUndefined:ne,ZodNull:ie,ZodAny:oe,ZodUnknown:de,ZodNever:ue,ZodVoid:ce,ZodArray:le,ZodObject:he,ZodUnion:me,ZodDiscriminatedUnion:ye,ZodIntersection:_e,ZodTuple:ge,ZodRecord:be,ZodMap:ke,ZodSet:xe,ZodFunction:Ze,ZodLazy:we,ZodLiteral:Te,ZodEnum:Oe,ZodNativeEnum:Ce,ZodPromise:Ne,ZodEffects:Ae,ZodTransformer:Ae,ZodOptional:Se,ZodNullable:je,ZodDefault:Ee,ZodCatch:Fe,ZodNaN:Ie,BRAND:Re,ZodBranded:Ke,ZodPipeline:$e,ZodReadonly:Me,custom:Le,Schema:A,ZodSchema:A,late:ze,get ZodFirstPartyTypeKind(){return e.ZodFirstPartyTypeKind},coerce:Ct,any:et,array:rt,bigint:Je,boolean:Ye,date:He,discriminatedUnion:dt,effect:bt,enum:vt,function:mt,instanceof:Ue,intersection:ut,lazy:ft,literal:yt,map:pt,nan:qe,nativeEnum:_t,never:at,null:Qe,nullable:xt,number:We,object:nt,oboolean:Ot,onumber:Pt,optional:kt,ostring:Tt,pipeline:wt,preprocess:Zt,promise:gt,record:lt,set:ht,strictObject:it,string:Be,symbol:Ge,transformer:bt,tuple:ct,undefined:Xe,union:ot,unknown:tt,void:st,NEVER:Nt,ZodIssueCode:r,quotelessJson:n,ZodError:i});e.BRAND=Re,e.DIRTY=y,e.EMPTY_PATH=p,e.INVALID=f,e.NEVER=Nt,e.OK=v,e.ParseStatus=m,e.Schema=A,e.ZodAny=oe,e.ZodArray=le,e.ZodBigInt=te,e.ZodBoolean=ae,e.ZodBranded=Ke,e.ZodCatch=Fe,e.ZodDate=se,e.ZodDefault=Ee,e.ZodDiscriminatedUnion=ye,e.ZodEffects=Ae,e.ZodEnum=Oe,e.ZodError=i,e.ZodFunction=Ze,e.ZodIntersection=_e,e.ZodIssueCode=r,e.ZodLazy=we,e.ZodLiteral=Te,e.ZodMap=ke,e.ZodNaN=Ie,e.ZodNativeEnum=Ce,e.ZodNever=ue,e.ZodNull=ie,e.ZodNullable=je,e.ZodNumber=ee,e.ZodObject=he,e.ZodOptional=Se,e.ZodParsedType=a,e.ZodPipeline=$e,e.ZodPromise=Ne,e.ZodReadonly=Me,e.ZodRecord=be,e.ZodSchema=A,e.ZodSet=xe,e.ZodString=X,e.ZodSymbol=re,e.ZodTransformer=Ae,e.ZodTuple=ge,e.ZodType=A,e.ZodUndefined=ne,e.ZodUnion=me,e.ZodUnknown=de,e.ZodVoid=ce,e.addIssueToContext=h,e.any=et,e.array=rt,e.bigint=Je,e.boolean=Ye,e.coerce=Ct,e.custom=Le,e.date=He,e.datetimeRegex=Y,e.default=At,e.defaultErrorMap=o,e.discriminatedUnion=dt,e.effect=bt,e.enum=vt,e.function=mt,e.getErrorMap=c,e.getParsedType=s,e.instanceof=Ue,e.intersection=ut,e.isAborted=_,e.isAsync=k,e.isDirty=g,e.isValid=b,e.late=ze,e.lazy=ft,e.literal=yt,e.makeIssue=l,e.map=pt,e.nan=qe,e.nativeEnum=_t,e.never=at,e.null=Qe,e.nullable=xt,e.number=We,e.object=nt,e.oboolean=Ot,e.onumber=Pt,e.optional=kt,e.ostring=Tt,e.pipeline=wt,e.preprocess=Zt,e.promise=gt,e.quotelessJson=n,e.record=lt,e.set=ht,e.setErrorMap=u,e.strictObject=it,e.string=Be,e.symbol=Ge,e.transformer=bt,e.tuple=ct,e[void 0]=Xe,e.union=ot,e.unknown=tt,e.void=st,e.z=At,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=/sm/faeed0596d43c60cf0df488e38219b3725a534b9e2fba99cb50ebc3c0df8e313.map \ No newline at end of file diff --git a/ui/site/apps/Forum/Forum.js b/ui/site/apps/Forum/Forum.js index 87cb461..607d354 100644 --- a/ui/site/apps/Forum/Forum.js +++ b/ui/site/apps/Forum/Forum.js @@ -1,3 +1,5 @@ +import './MessagesPanel.js' + css(` forum- { font-family: 'Bona'; @@ -23,8 +25,6 @@ css(` `) class Forum extends Shadow { - friends = [] - conversations = [] render() { ZStack(() => { @@ -46,13 +46,25 @@ class Forum extends Shadow { .gap(0, em) VStack(() => { - input("Message Hyperia", "80%") + + MessagesPanel() + + input("Message Hyperia", "93%") .paddingVertical(1, em) + .paddingHorizontal(2, em) .color("var(--accent)") .background("var(--darkbrown)") .marginBottom(6, em) .border("none") + .fontSize(1, em) + .onKeyDown(function (e) { + if (e.key === "Enter") { + window.Socket.send({app: "FORUM", operation: "SEND", msg: {forum: "HY", text: this.value }}) + this.value = "" + } + }) }) + .gap(1, em) .width(100, pct) .alignHorizontal("center") .alignVertical("end") @@ -120,6 +132,8 @@ class Forum extends Shadow { .width(100, pct) .height(100, pct) } + + } register(Forum) \ No newline at end of file diff --git a/ui/site/apps/Forum/MessagesPanel.js b/ui/site/apps/Forum/MessagesPanel.js new file mode 100644 index 0000000..e75d7b6 --- /dev/null +++ b/ui/site/apps/Forum/MessagesPanel.js @@ -0,0 +1,83 @@ +class MessagesPanel extends Shadow { + forums = [ + "HY" + ] + messages = [] + + render() { + VStack(() => { + if(this.messages.length > 0) { + for(let i=0; i { + HStack(() => { + p(message.sentBy) + .fontWeight("bold") + .marginBottom(0.3, em) + + p(this.formatTime(message.time)) + .opacity(0.2) + .marginLeft(1, em) + }) + p(message.text) + }) + } + } else { + div() + .borderRadius(100, pct) + .width(2, em).height(2, em) + .x(45, pct).y(50, pct) + .center() + .backgroundColor("var(--accent") + .transition("transform 1.75s ease-in-out") + .onAppear(function () { + let growing = true; + + setInterval(() => { + if (growing) { + this.style.transform = "scale(1.5)"; + } else { + this.style.transform = "scale(0.7)"; + } + growing = !growing; + }, 750); + }); + } + }) + .gap(1, em) + .position("relative") + .overflow("scroll") + .height(95, pct) + .width(93, pct) + .paddingTop(2, em) + .paddingBottom(2, em) + .paddingHorizontal(2, em) + .backgroundColor("var(--darkbrown)") + .onAppear(async () => { + console.log("appear") + let res = await Socket.send({app: "FORUM", operation: "GET", msg: {forum: "HY", number: 100}}) + if(!res) console.error("failed to get messages") + if(res.msg.length > 0 && this.messages.length === 0) { + console.log("rerendering", res.msg) + this.messages = res.msg + this.rerender() + } + window.addEventListener("new-message", (e) => { + this.messages = e.detail + this.rerender() + }) + }) + .scrollTop = this.scrollHeight + } + + formatTime(str) { + // Extract the time part with am/pm + const match = str.match(/-(\d+:\d+):\d+.*(am|pm)/i); + if (!match) return null; + + const [_, hourMin, ampm] = match; + return hourMin + ampm.toLowerCase(); + } +} + +register(MessagesPanel) \ No newline at end of file diff --git a/ui/site/components/AppMenu.js b/ui/site/components/AppMenu.js index adb29cf..96a507e 100644 --- a/ui/site/components/AppMenu.js +++ b/ui/site/components/AppMenu.js @@ -9,14 +9,13 @@ css(` app-menu.minimized { color: var(--accent); transform: translate(-50%, 65%); - border: 1px solid var(--accent); + border: 0.2px solid var(--accent); padding-top: 0.5em; padding-left: 2em; padding-right: 2em; padding-bottom: 4em; bottom: 1em; border-radius: 12px; - background-color: var(--green); } app-menu p { diff --git a/ui/site/components/ProfileButton.js b/ui/site/components/ProfileButton.js index 9eb609d..d218f30 100644 --- a/ui/site/components/ProfileButton.js +++ b/ui/site/components/ProfileButton.js @@ -10,16 +10,45 @@ class ProfileButton extends Shadow { .borderRadius(5, px) ProfileMenu() + .x(0, vw).y(4, em) + .center() }) .display("block") - .onHover((hovering) => { + .onAppear(async () => { + try { + const res = await fetch("/profile", { + method: "GET", + credentials: "include", + headers: { + "Content-Type": "application/json" + } + }); + + if (!res.ok) throw new Error("Failed to fetch profile"); + + const profile = await res.json(); + console.log(profile); + return profile; + + } catch (err) { + console.error(err); + } + }) + .onHover((hovering, e) => { console.log(hovering) - if(hovering) { + console.log(e.target) + if(hovering && !e.target.matches("profile-menu")) { this.$("img").backgroundColor("var(--accent)") - this.$("img").border("1px solid black") - } else { + this.$("img").style.outline = "1px solid black" + } else if(!e.target.matches("profile-menu")) { this.$("img").backgroundColor("") - this.$("img").border("") + this.$("img").style.outline = "" + } + }) + .onClick((done) => { + console.log(done) + if(done) { + this.$("profile-menu").style.display = "" } }) diff --git a/ui/site/components/ProfileMenu.js b/ui/site/components/ProfileMenu.js index d36355d..0926770 100644 --- a/ui/site/components/ProfileMenu.js +++ b/ui/site/components/ProfileMenu.js @@ -1,51 +1,11 @@ -css(` - profile-menu { - position: absolute; - right: -.5em; - top: -.3em; - width: 0; - height: 0; - background-color: rgba(255, 223, 180, 0.56); - color: black; - transition: width 0.2s, height 0.2s; - border-radius: 12px; - } - - profile-menu * { - transition: opacity 0.3s; - } - - profile-menu.closed * { - opacity: 0; - } - - profile-menu.open { - width: 10em; - height: 15em; - display: block; - } - - profile-menu.open * { - opacity: 100%; - } -`) - class ProfileMenu extends Shadow { render() { ZStack(() => { - if(this.classList.contains("open")) { - setTimeout(() => { - // this.innerHTML = /* html */` - // sign out - //

Profile

- // ` - }, 200) - } - }) - - util.observeClassChange(this, (cl) => { + p("profile") }) + .backgroundColor("var(--accent)") + .display("none") } } diff --git a/ui/site/index.html b/ui/site/index.html index fa1dd9a..ca92388 100644 --- a/ui/site/index.html +++ b/ui/site/index.html @@ -6,6 +6,7 @@ + diff --git a/ui/site/index.js b/ui/site/index.js index f0db67a..a22a951 100644 --- a/ui/site/index.js +++ b/ui/site/index.js @@ -1,5 +1,5 @@ -import ConnectionHandler from "./ws/ConnectionHandler.js" -window.ConnectionHandler = new ConnectionHandler() - +import Socket from "./ws/Socket.js" import "./components/Home.js" + +window.Socket = new Socket() Home() \ No newline at end of file diff --git a/ui/site/ws/Connection.js b/ui/site/ws/Connection.js index 18be867..69232ff 100644 --- a/ui/site/ws/Connection.js +++ b/ui/site/ws/Connection.js @@ -4,8 +4,9 @@ class Connection { linkCreated; wsStatus; - constructor() { + constructor(receiveCB) { this.init() + this.receiveCB = receiveCB } init() { @@ -17,41 +18,13 @@ class Connection { this.ws.addEventListener('open', () => { this.connectionTries = 0 console.log("Websocket connection established."); - this.ws.addEventListener('message', this.onMessage) + this.ws.addEventListener('message', this.receiveCB) }); this.ws.addEventListener("close", () => { this.checkOpen(); console.log('Websocket Closed') }) } - - onMessage = (event) => { - let message = event.data; - let messageSplit = message.split('|'); - - switch(messageSplit[0]) { - case 'connected': - Forms.connected(messageSplit[1], messageSplit[2]) - break; - case 'disconnected': - Forms.disconnected(messageSplit[1]) - break; - case 'UPDATE-SIZE': - updateFileSize(messageSplit[1], messageSplit[2]); - break; - case 'URL-TITLE-RESPONSE': - this.updateLinkTitle(messageSplit[1]); - break; - default: - console.log('Websocket message:', message); - break; - } - - - if (messageSplit[1] == 'CSS-LINK') { - this.createCSSLink(message); - } - } async checkOpen() { if (this.ws.readyState === WebSocket.OPEN) { @@ -70,65 +43,20 @@ class Connection { }); } - sendMessage = (msg) => { + send = (msg) => { + console.log("sending") if (this.ws.readyState === WebSocket.OPEN) { this.ws.send(msg); } + else if(this.connectionTries === 0) { + setTimeout(() => { + this.send(msg) + }, 100) + } else { - console.log('No websocket connection: Cannot send message'); + console.error('No websocket connection: Cannot send message'); } } - - updateCSS = async (updateStyle, newValue) => { - let currentSpace = window.wrapper.getAttribute("name").replace(/ /g,'%20') - let currentFolder = window.location.pathname; - //create the inital link - this.linkCreated = false; - let cssIncomingText = "" - Array.from(document.styleSheets).forEach(el => { - if(el?.href?.includes?.(`.${currentSpace}.css`)) { - this.linkCreated = true; - - } - }) - let currentSpaceDataAttr = window.wrapper.getAttribute("name"); - let cssInit = `parchment-page[name="${currentSpaceDataAttr}"] {background-color: #e9c9a0;} parchment-page[name="${currentSpaceDataAttr}"] > p.text {font-family: ${newValue};} parchment-page[name="${currentSpaceDataAttr}"] > file-::before, parchment-page[name="${currentSpaceDataAttr}"] > image-::before, parchment-page[name="${currentSpaceDataAttr}"] > parchment-page::before {font-family: ${newValue};font-weight: 400;} parchment-page[name="${currentSpaceDataAttr}"] > space-select-outline > file-::before, parchment-page[name="${currentSpaceDataAttr}"] > select-outline > *, parchment-page[name="${currentSpaceDataAttr}"] > select-outline > image-::before ,parchment-page[name="${currentSpaceDataAttr}"] > space-select-outline > parchment-page::before, parchment-page[name="${currentSpaceDataAttr}"] > a, parchment-page[name="${currentSpaceDataAttr}"] > input-box {font-family: ${newValue}; font-weight: 400;}` - cssIncomingText += cssInit - - let CSSRawData = `REQUEST|update-css|${currentFolder}|${cssIncomingText}|` - await this.checkOpen() - this.ws.send(CSSRawData) - } - - createCSSLink = (wsMessage) => { - let retrieveHref = wsMessage; - var link = document.createElement("link"); - link.rel = "stylesheet"; - link.id = window.wrapper.getAttribute('name')+"-css" - link.href = retrieveHref; - - let retrieveStyleLinks = document.querySelectorAll(`[href='${retrieveHref}']`); - if (retrieveStyleLinks[0] !== undefined) { - retrieveStyleLinks[0].remove(); - } - window.wrapper.prepend(link); - } - - scrapeExternalHTMLTitle = async (href) => { - let req = `REQUEST|scrape-title|${href}|` - await this.checkOpen() - this.ws.send(req) - } - - updateLinkTitle = (title) => { - let link = document.querySelectorAll('.convert-to-title')[0] - if (title !=="") { - link.innerHTML += title; - } else { - link.innerHTML += link.getAttribute('href') - } - link.classList.remove('convert-to-title') - } } export default Connection \ No newline at end of file diff --git a/ui/site/ws/ConnectionHandler.js b/ui/site/ws/ConnectionHandler.js deleted file mode 100644 index a7629b8..0000000 --- a/ui/site/ws/ConnectionHandler.js +++ /dev/null @@ -1,22 +0,0 @@ -import Connection from "./Connection.js"; - -export default class ConnectionHandler { - connection; - disabled = true; - - constructor() { - this.connection = new Connection(); - } - - isOpen() { - if(this.connection.checkOpen()) { - return true; - } else { - return false; - } - } - - send(msg) { - this.connection.sendMessage(msg) - } -} \ No newline at end of file diff --git a/ui/site/ws/Socket.js b/ui/site/ws/Socket.js new file mode 100644 index 0000000..4497de6 --- /dev/null +++ b/ui/site/ws/Socket.js @@ -0,0 +1,46 @@ +import Connection from "./Connection.js"; + +export default class Socket { + connection; + disabled = true; + requestID = 1; + pending = new Map(); + + constructor() { + this.connection = new Connection(this.receive); + } + + isOpen() { + if(this.connection.checkOpen()) { + return true; + } else { + return false; + } + } + + send(msg) { + return new Promise(resolve => { + const id = (++this.requestID).toString(); + this.pending.set(id, resolve); + this.connection.send(JSON.stringify({ id, ...msg })); + }); + } + + receive = (event) => { + const msg = JSON.parse(event.data); + if (msg.id && this.pending.has(msg.id)) { + this.pending.get(msg.id)(msg); + this.pending.delete(msg.id); + return; + } else { + this.onBroadcast(msg) + } + } + + onBroadcast(msg) { + console.log(msg.msg) + window.dispatchEvent(new CustomEvent(msg.event, { + detail: msg.msg + })); + } +} \ No newline at end of file