arcanajs 4.0.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/529.js +2 -0
- package/dist/529.js.map +1 -0
- package/dist/630.js +3 -0
- package/dist/630.js.LICENSE.txt +14 -0
- package/dist/630.js.map +1 -0
- package/dist/arcanajs.auth.js +3 -0
- package/dist/arcanajs.auth.js.LICENSE.txt +14 -0
- package/dist/arcanajs.auth.js.map +1 -0
- package/dist/arcanajs.js +1 -1
- package/dist/arcanajs.js.map +1 -1
- package/dist/arcanajs.mail.js +2 -0
- package/dist/arcanajs.mail.js.map +1 -0
- package/dist/arcanajs.validator.js +2 -0
- package/dist/arcanajs.validator.js.map +1 -0
- package/dist/arcanox.js +1 -1
- package/dist/arcanox.js.map +1 -1
- package/dist/cli/commands/dependency.d.ts +1 -0
- package/dist/cli/commands/make/Controller.d.ts +3 -0
- package/dist/cli/commands/make/Factory.d.ts +2 -0
- package/dist/cli/commands/make/Middleware.d.ts +1 -0
- package/dist/cli/commands/make/Migration.d.ts +2 -0
- package/dist/cli/commands/make/Model.d.ts +2 -0
- package/dist/cli/commands/make/Provider.d.ts +1 -0
- package/dist/cli/commands/make/Request.d.ts +1 -0
- package/dist/cli/commands/make/Seeder.d.ts +2 -0
- package/dist/cli/index.js +1 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/utils/toPascalCase.d.ts +1 -0
- package/dist/cli/utils/writeFile.d.ts +1 -0
- package/dist/lib/arcanox/providers/DatabaseProvider.d.ts +9 -4
- package/dist/lib/auth/AuthProvider.d.ts +10 -0
- package/dist/lib/auth/JWTService.d.ts +11 -0
- package/dist/lib/auth/SessionManager.d.ts +4 -0
- package/dist/lib/auth/middleware/AuthMiddleware.d.ts +5 -0
- package/dist/lib/auth/middleware/AuthenticatedMiddleware.d.ts +5 -0
- package/dist/lib/auth/middleware/GuestMiddleware.d.ts +5 -0
- package/dist/lib/auth/middleware/RoleMiddleware.d.ts +7 -0
- package/dist/lib/auth/types/AuthConfig.d.ts +24 -0
- package/dist/lib/auth/types/JWTPayload.d.ts +10 -0
- package/dist/lib/auth/types/index.d.ts +2 -0
- package/dist/lib/auth/utils/PasswordHasher.d.ts +16 -0
- package/dist/lib/auth/utils/TokenBlacklist.d.ts +9 -0
- package/dist/lib/index.arcanox.d.ts +16 -2
- package/dist/lib/index.auth.d.ts +11 -0
- package/dist/lib/index.client.d.ts +2 -0
- package/dist/lib/index.mail.d.ts +8 -0
- package/dist/lib/index.server.d.ts +4 -6
- package/dist/lib/index.validator.d.ts +6 -0
- package/dist/lib/mail/MailProvider.d.ts +10 -0
- package/dist/lib/mail/MailService.d.ts +57 -0
- package/dist/lib/mail/Mailable.d.ts +106 -0
- package/dist/lib/mail/index.d.ts +6 -0
- package/dist/lib/mail/queue/MailQueue.d.ts +51 -0
- package/dist/lib/mail/queue/index.d.ts +1 -0
- package/dist/lib/mail/types/MailConfig.d.ts +146 -0
- package/dist/lib/mail/types/index.d.ts +1 -0
- package/dist/lib/mail/utils/TemplateRenderer.d.ts +34 -0
- package/dist/lib/mail/utils/index.d.ts +1 -0
- package/dist/lib/server/ArcanaJSServer.d.ts +15 -8
- package/dist/lib/server/Container.d.ts +8 -0
- package/dist/lib/server/Router.d.ts +23 -33
- package/dist/lib/server/support/ServiceProvider.d.ts +4 -0
- package/dist/lib/validation/Validator.d.ts +55 -0
- package/dist/types/global.d.ts +102 -0
- package/package.json +68 -15
- package/dist/lib/arcanox/index.d.ts +0 -13
- package/dist/lib/server/validation/Validator.d.ts +0 -12
- /package/dist/lib/{server/validation → validation}/ValidationException.d.ts +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(()=>{"use strict";var e={118:e=>{e.exports=require("nodemailer-mailgun-transport")},156:e=>{e.exports=require("handlebars")},511:(e,t,i)=>{i.d(t,{W:()=>r});class r{message={};to(e,t){return this.message.to=e,this}from(e,t){return this.message.from={address:e,name:t},this}subject(e){return this.message.subject=e,this}view(e,t){return this.viewName=e,this.viewData=t,this}html(e){return this.message.html=e,this}text(e){return this.message.text=e,this}cc(e){return this.message.cc=e,this}bcc(e){return this.message.bcc=e,this}replyTo(e){return this.message.replyTo=e,this}attach(e){return this.message.attachments||(this.message.attachments=[]),this.message.attachments.push(e),this}attachFromPath(e,t){return this.attach({filename:t||e.split("/").pop()||"attachment",path:e})}attachData(e,t,i){return this.attach({filename:t,content:e,contentType:i})}priority(e){return this.message.priority=e,this}withHeaders(e){return this.message.headers={...this.message.headers,...e},this}getMessage(){return this.build(),{message:this.message,viewName:this.viewName,viewData:this.viewData}}async send(){const{MailService:e}=await Promise.resolve().then(i.bind(i,821));await e.send(this)}async queue(){const{MailService:e}=await Promise.resolve().then(i.bind(i,821));await e.queue(this)}}},635:(e,t,i)=>{i.d(t,{K:()=>n});const r=require("ejs"),s=require("fs"),a=require("path");class n{static init(e){this.config=e}static async render(e,t={}){if(!this.config)throw new Error("TemplateRenderer not initialized");const i=a.join(process.cwd(),this.config.viewsPath,`${e}.${"ejs"===this.config.engine?"ejs":"hbs"}`);if(!s.existsSync(i))throw new Error(`Template not found: ${i}`);let r;return r="ejs"===this.config.engine?await this.renderEJS(i,t):await this.renderHandlebars(i,t),this.config.defaultLayout&&this.config.layoutsPath&&(r=await this.applyLayout(r,t)),{html:r,text:this.htmlToText(r)}}static async renderEJS(e,t){return r.renderFile(e,t)}static async renderHandlebars(e,t){const r=i(156),a=s.readFileSync(e,"utf-8");return r.compile(a)(t)}static async applyLayout(e,t){var n;if(null===(n=this.config)||void 0===n||!n.layoutsPath||!this.config.defaultLayout)return e;const o=a.join(process.cwd(),this.config.layoutsPath,`${this.config.defaultLayout}.${"ejs"===this.config.engine?"ejs":"hbs"}`);if(!s.existsSync(o))return e;const c={...t,body:e};if("ejs"===this.config.engine)return r.renderFile(o,c);{const e=i(156),t=s.readFileSync(o,"utf-8");return e.compile(t)(c)}}static htmlToText(e){return e.replace(/<style[^>]*>.*?<\/style>/gi,"").replace(/<script[^>]*>.*?<\/script>/gi,"").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim()}}},638:e=>{e.exports=require("@aws-sdk/client-ses")},659:e=>{e.exports=require("ioredis")},821:(e,t,i)=>{i.d(t,{MailService:()=>o});const r=require("nodemailer");var s=i(511),a=i(996),n=i(635);class o{static async init(e){var t;this.config=e,this.transporter=await this.createTransporter(e),e.templates&&n.K.init(e.templates),null!==(t=e.queue)&&void 0!==t&&t.enabled&&await a.D.init(e.queue)}static async createTransporter(e){switch(e.default){case"smtp":return this.createSMTPTransporter(e.smtp);case"sendgrid":return this.createSendGridTransporter(e.sendgrid);case"mailgun":return this.createMailgunTransporter(e.mailgun);case"ses":return this.createSESTransporter(e.ses);case"log":return this.createLogTransporter();default:throw new Error(`Unsupported mail driver: ${e.default}`)}}static createSMTPTransporter(e){return r.createTransport({host:e.host,port:e.port,secure:e.secure,auth:e.auth,tls:e.tls})}static createSendGridTransporter(e){return r.createTransport({host:"smtp.sendgrid.net",port:587,auth:{user:"apikey",pass:e.apiKey}})}static createMailgunTransporter(e){const t=i(118);return r.createTransport(t({auth:{api_key:e.apiKey,domain:e.domain},host:e.host||"api.mailgun.net"}))}static createSESTransporter(e){const{SESClient:t,SendRawEmailCommand:s}=i(638),a={region:e.region};e.accessKeyId&&e.secretAccessKey&&(a.credentials={accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,sessionToken:e.sessionToken});const n={SES:{ses:new t(a),aws:{SendRawEmailCommand:s}}};return r.createTransport(n)}static createLogTransporter(){return r.createTransport({streamTransport:!0,newline:"unix",buffer:!0})}static async send(e){if(!this.transporter||!this.config)throw new Error("MailService not initialized. Call MailService.init() first.");let t;if(e instanceof s.W){const{message:i,viewName:r,viewData:s}=e.getMessage();if(r&&this.config.templates){const{html:e,text:t}=await n.K.render(r,s);i.html=e,i.text=t}t=i}else t=e;!t.from&&this.config.from&&(t.from=this.config.from),!t.replyTo&&this.config.replyTo&&(t.replyTo=this.config.replyTo.address);const i={...t,from:t.from?"string"==typeof t.from?t.from:t.from.name?`"${t.from.name}" <${t.from.address}>`:t.from.address:void 0};try{const e=await this.transporter.sendMail(i);"log"===this.config.default?(console.log("Email preview:"),console.log("To:",t.to),console.log("Subject:",t.subject),console.log("---")):console.log(`Email sent: ${e.messageId}`)}catch(e){throw console.error("Failed to send email:",e),e}}static async queue(e){var t;if(null===(t=this.config)||void 0===t||null===(t=t.queue)||void 0===t||!t.enabled)return this.send(e);await a.D.add(e)}static async sendRaw(e){return this.send(e)}static getConfig(){return this.config}static async verify(){if(!this.transporter)throw new Error("MailService not initialized");try{return await this.transporter.verify(),!0}catch(e){return console.error("Mail transporter verification failed:",e),!1}}}},996:(e,t,i)=>{i.d(t,{D:()=>r});class r{static queue=[];static processing=!1;static async init(e){this.config=e,"redis"===e.driver&&e.redis&&await this.initRedis(e.redis),this.startProcessing()}static async initRedis(e){try{const t=i(659);this.redisClient=new t({host:e.host,port:e.port,password:e.password,db:e.db||0}),this.redisClient.on("error",e=>{console.error("Redis connection error:",e)})}catch(e){console.warn("Redis not available, falling back to memory queue"),this.config.driver="memory"}}static async add(e){var t;const i={id:this.generateId(),mailable:e,attempts:0,createdAt:new Date};"redis"===(null===(t=this.config)||void 0===t?void 0:t.driver)&&this.redisClient?await this.redisClient.lpush("mail:queue",JSON.stringify(i)):this.queue.push(i)}static startProcessing(){this.processing||(this.processing=!0,setInterval(async()=>{await this.processNext()},1e3))}static async processNext(){var e;let t=null;if("redis"===(null===(e=this.config)||void 0===e?void 0:e.driver)&&this.redisClient){const e=await this.redisClient.rpop("mail:queue");e&&(t=JSON.parse(e))}else t=this.queue.shift()||null;if(t)if(t.nextRetry&&new Date<t.nextRetry)await this.add(t.mailable);else try{await t.mailable.send()}catch(e){await this.handleFailedJob(t,e)}}static async handleFailedJob(e,t){var i;const r=(null===(i=this.config)||void 0===i?void 0:i.retries)||3;if(e.attempts++,e.attempts<r){var s;const t=((null===(s=this.config)||void 0===s?void 0:s.retryDelay)||60)*Math.pow(2,e.attempts-1);e.nextRetry=new Date(Date.now()+1e3*t),console.warn(`Mail job ${e.id} failed (attempt ${e.attempts}/${r}), retrying in ${t}s`),await this.add(e.mailable)}else console.error(`Mail job ${e.id} failed after ${r} attempts:`,t),await this.storeFailedJob(e,t)}static async storeFailedJob(e,t){var i;const r={...e,error:t.message,failedAt:new Date};"redis"===(null===(i=this.config)||void 0===i?void 0:i.driver)&&this.redisClient?await this.redisClient.lpush("mail:failed",JSON.stringify(r)):console.error("Failed mail job:",r)}static generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static async size(){var e;return"redis"===(null===(e=this.config)||void 0===e?void 0:e.driver)&&this.redisClient?await this.redisClient.llen("mail:queue"):this.queue.length}static async clear(){var e;"redis"===(null===(e=this.config)||void 0===e?void 0:e.driver)&&this.redisClient?await this.redisClient.del("mail:queue"):this.queue=[]}}}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var a=t[r]={exports:{}};return e[r](a,a.exports,i),a.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};i.r(r),i.d(r,{MailProvider:()=>o,MailQueue:()=>c.D,MailService:()=>n.MailService,Mailable:()=>s.W,TemplateRenderer:()=>l.K});var s=i(511);class a{constructor(e){this.app=e}register(){}boot(){}async shutdown(){}}var n=i(821);class o extends a{async register(){let e;console.log("⚙️ MailProvider: Initializing...");try{e=this.app.container.resolve("MailConfig"),console.log("✓ MailProvider: Configuration loaded successfully")}catch(e){return void console.warn("⚠ MailProvider: No configuration found - Skipping setup")}try{await n.MailService.init(e),console.log(`✓ MailProvider: Service initialized with driver '${e.default}'`),this.app.container.singleton("MailConfig",()=>e),this.app.container.singleton("MailService",()=>n.MailService),console.log("✅ MailProvider: Ready")}catch(e){throw console.error("✗ MailProvider: Initialization failed",e),e}}async boot(){try{const e=this.app.container.resolve("MailConfig");e&&"log"!==e.default&&(console.log("⚙️ MailProvider: Verifying transporter connection..."),await n.MailService.verify()&&console.log("✓ MailProvider: Transporter verified successfully"))}catch(e){console.warn("⚠ MailProvider: Transporter verification failed",e)}}}var c=i(996),l=i(635),d=exports;for(var h in r)d[h]=r[h];r.__esModule&&Object.defineProperty(d,"__esModule",{value:!0})})();
|
|
2
|
+
//# sourceMappingURL=arcanajs.mail.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"arcanajs.mail.js","mappings":"kCAAAA,EAAOC,QAAUC,QAAQ,+B,UCAzBF,EAAOC,QAAUC,QAAQ,a,iCCwBlB,MAAeC,EACVC,QAAgC,CAAC,EAa3CC,EAAAA,CAAGC,EAA4BC,GAE7B,OADAC,KAAKJ,QAAQC,GAAKC,EACXE,IACT,CAKAC,IAAAA,CAAKH,EAAiBC,GAEpB,OADAC,KAAKJ,QAAQK,KAAO,CAAEH,UAASC,QACxBC,IACT,CAKAE,OAAAA,CAAQA,GAEN,OADAF,KAAKJ,QAAQM,QAAUA,EAChBF,IACT,CAKAG,IAAAA,CAAKC,EAAkBC,GAGrB,OAFAL,KAAKM,SAAWF,EAChBJ,KAAKO,SAAWF,EACTL,IACT,CAKAQ,IAAAA,CAAKC,GAEH,OADAT,KAAKJ,QAAQY,KAAOC,EACbT,IACT,CAKAU,IAAAA,CAAKD,GAEH,OADAT,KAAKJ,QAAQc,KAAOD,EACbT,IACT,CAKAW,EAAAA,CAAGb,GAED,OADAE,KAAKJ,QAAQe,GAAKb,EACXE,IACT,CAKAY,GAAAA,CAAId,GAEF,OADAE,KAAKJ,QAAQgB,IAAMd,EACZE,IACT,CAKAa,OAAAA,CAAQf,GAEN,OADAE,KAAKJ,QAAQiB,QAAUf,EAChBE,IACT,CAKAc,MAAAA,CAAOC,GAK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,QAAnBA,EAAOgC,UACnB0C,QAAQC,IAAI,+DACW/E,EAAY,YAAAqF,UAEjCP,QAAQC,IAAI,qDAGlB,CAAE,MAAOE,GACPH,QAAQmB,KAAK,kDAAmDhB,EAClE,CACF,E","sources":["webpack://arcanajs/external commonjs \"nodemailer-mailgun-transport\"","webpack://arcanajs/external commonjs \"handlebars\"","webpack://arcanajs/./src/lib/mail/Mailable.ts","webpack://arcanajs/external commonjs \"ejs\"","webpack://arcanajs/external node-commonjs \"fs\"","webpack://arcanajs/external node-commonjs \"path\"","webpack://arcanajs/./src/lib/mail/utils/TemplateRenderer.ts","webpack://arcanajs/external commonjs \"@aws-sdk/client-ses\"","webpack://arcanajs/external commonjs \"ioredis\"","webpack://arcanajs/external commonjs \"nodemailer\"","webpack://arcanajs/./src/lib/mail/MailService.ts","webpack://arcanajs/./src/lib/mail/queue/MailQueue.ts","webpack://arcanajs/webpack/bootstrap","webpack://arcanajs/webpack/runtime/define property getters","webpack://arcanajs/webpack/runtime/hasOwnProperty shorthand","webpack://arcanajs/webpack/runtime/make namespace object","webpack://arcanajs/./src/lib/server/support/ServiceProvider.ts","webpack://arcanajs/./src/lib/mail/MailProvider.ts"],"sourcesContent":["module.exports = require(\"nodemailer-mailgun-transport\");","module.exports = require(\"handlebars\");","import { MailAttachment, MailMessage } from \"./types\";\n\n/**\n * Abstract base class for creating email messages\n *\n * @example\n * ```typescript\n * class WelcomeEmail extends Mailable {\n * constructor(private user: User) {\n * super();\n * }\n *\n * build() {\n * return this\n * .to(this.user.email)\n * .subject('Welcome to ArcanaJS!')\n * .view('emails/welcome', { name: this.user.name });\n * }\n * }\n *\n * // Send the email\n * await new WelcomeEmail(user).send();\n * ```\n */\nexport abstract class Mailable {\n protected message: Partial<MailMessage> = {};\n protected viewName?: string;\n protected viewData?: Record<string, any>;\n\n /**\n * Build the email message\n * Must be implemented by subclasses\n */\n abstract build(): this;\n\n /**\n * Set the recipient(s)\n */\n to(address: string | string[], name?: string): this {\n this.message.to = address;\n return this;\n }\n\n /**\n * Set the sender\n */\n from(address: string, name?: string): this {\n this.message.from = { address, name };\n return this;\n }\n\n /**\n * Set the email subject\n */\n subject(subject: string): this {\n this.message.subject = subject;\n return this;\n }\n\n /**\n * Set the email view template\n */\n view(template: string, data?: Record<string, any>): this {\n this.viewName = template;\n this.viewData = data;\n return this;\n }\n\n /**\n * Set HTML content directly\n */\n html(content: string): this {\n this.message.html = content;\n return this;\n }\n\n /**\n * Set plain text content\n */\n text(content: string): this {\n this.message.text = content;\n return this;\n }\n\n /**\n * Add CC recipient(s)\n */\n cc(address: string | string[]): this {\n this.message.cc = address;\n return this;\n }\n\n /**\n * Add BCC recipient(s)\n */\n bcc(address: string | string[]): this {\n this.message.bcc = address;\n return this;\n }\n\n /**\n * Set reply-to address\n */\n replyTo(address: string): this {\n this.message.replyTo = address;\n return this;\n }\n\n /**\n * Add an attachment\n */\n attach(attachment: MailAttachment): this {\n if (!this.message.attachments) {\n this.message.attachments = [];\n }\n this.message.attachments.push(attachment);\n return this;\n }\n\n /**\n * Attach a file from path\n */\n attachFromPath(path: string, filename?: string): this {\n return this.attach({\n filename: filename || path.split(\"/\").pop() || \"attachment\",\n path,\n });\n }\n\n /**\n * Attach data as a file\n */\n attachData(\n content: string | Buffer,\n filename: string,\n contentType?: string\n ): this {\n return this.attach({\n filename,\n content,\n contentType,\n });\n }\n\n /**\n * Set email priority\n */\n priority(level: \"high\" | \"normal\" | \"low\"): this {\n this.message.priority = level;\n return this;\n }\n\n /**\n * Add custom headers\n */\n withHeaders(headers: Record<string, string>): this {\n this.message.headers = { ...this.message.headers, ...headers };\n return this;\n }\n\n /**\n * Get the built message\n * @internal\n */\n getMessage(): {\n message: Partial<MailMessage>;\n viewName?: string;\n viewData?: Record<string, any>;\n } {\n this.build();\n return {\n message: this.message,\n viewName: this.viewName,\n viewData: this.viewData,\n };\n }\n\n /**\n * Send the email immediately\n */\n async send(): Promise<void> {\n const { MailService } = await import(\"./MailService\");\n await MailService.send(this);\n }\n\n /**\n * Queue the email for async sending\n */\n async queue(): Promise<void> {\n const { MailService } = await import(\"./MailService\");\n await MailService.queue(this);\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"ejs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"fs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"path\");","import * as ejs from \"ejs\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { MailTemplateConfig } from \"../types\";\n\n/**\n * Template renderer for email views\n */\nexport class TemplateRenderer {\n private static config?: MailTemplateConfig;\n\n /**\n * Initialize the template renderer\n */\n static init(config: MailTemplateConfig) {\n this.config = config;\n }\n\n /**\n * Render a template to HTML\n */\n static async render(\n templateName: string,\n data: Record<string, any> = {}\n ): Promise<{ html: string; text: string }> {\n if (!this.config) {\n throw new Error(\"TemplateRenderer not initialized\");\n }\n\n const templatePath = path.join(\n process.cwd(),\n this.config.viewsPath,\n `${templateName}.${this.config.engine === \"ejs\" ? \"ejs\" : \"hbs\"}`\n );\n\n if (!fs.existsSync(templatePath)) {\n throw new Error(`Template not found: ${templatePath}`);\n }\n\n let html: string;\n\n if (this.config.engine === \"ejs\") {\n html = await this.renderEJS(templatePath, data);\n } else {\n html = await this.renderHandlebars(templatePath, data);\n }\n\n // Apply layout if configured\n if (this.config.defaultLayout && this.config.layoutsPath) {\n html = await this.applyLayout(html, data);\n }\n\n // Generate plain text version\n const text = this.htmlToText(html);\n\n return { html, text };\n }\n\n /**\n * Render EJS template\n */\n private static async renderEJS(\n templatePath: string,\n data: Record<string, any>\n ): Promise<string> {\n return ejs.renderFile(templatePath, data);\n }\n\n /**\n * Render Handlebars template\n */\n private static async renderHandlebars(\n templatePath: string,\n data: Record<string, any>\n ): Promise<string> {\n const Handlebars = require(\"handlebars\");\n const template = fs.readFileSync(templatePath, \"utf-8\");\n const compiled = Handlebars.compile(template);\n return compiled(data);\n }\n\n /**\n * Apply layout to rendered content\n */\n private static async applyLayout(\n content: string,\n data: Record<string, any>\n ): Promise<string> {\n if (!this.config?.layoutsPath || !this.config.defaultLayout) {\n return content;\n }\n\n const layoutPath = path.join(\n process.cwd(),\n this.config.layoutsPath,\n `${this.config.defaultLayout}.${\n this.config.engine === \"ejs\" ? \"ejs\" : \"hbs\"\n }`\n );\n\n if (!fs.existsSync(layoutPath)) {\n return content;\n }\n\n const layoutData = { ...data, body: content };\n\n if (this.config.engine === \"ejs\") {\n return ejs.renderFile(layoutPath, layoutData);\n } else {\n const Handlebars = require(\"handlebars\");\n const template = fs.readFileSync(layoutPath, \"utf-8\");\n const compiled = Handlebars.compile(template);\n return compiled(layoutData);\n }\n }\n\n /**\n * Convert HTML to plain text\n */\n private static htmlToText(html: string): string {\n return html\n .replace(/<style[^>]*>.*?<\\/style>/gi, \"\")\n .replace(/<script[^>]*>.*?<\\/script>/gi, \"\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n }\n}\n","module.exports = require(\"@aws-sdk/client-ses\");","module.exports = require(\"ioredis\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"nodemailer\");","import * as nodemailer from \"nodemailer\";\nimport { Mailable } from \"./Mailable\";\nimport { MailQueue } from \"./queue/MailQueue\";\nimport {\n MailConfig,\n MailgunConfig,\n MailMessage,\n MailTransporter,\n SendGridConfig,\n SESConfig,\n SMTPConfig,\n} from \"./types\";\nimport { TemplateRenderer } from \"./utils/TemplateRenderer\";\n\n/**\n * Core mail service for sending emails\n */\nexport class MailService {\n private static config?: MailConfig;\n private static transporter?: MailTransporter;\n\n /**\n * Initialize the mail service\n */\n static async init(config: MailConfig) {\n this.config = config;\n this.transporter = await this.createTransporter(config);\n\n // Initialize template renderer if configured\n if (config.templates) {\n TemplateRenderer.init(config.templates);\n }\n\n // Initialize queue if enabled\n if (config.queue?.enabled) {\n await MailQueue.init(config.queue);\n }\n }\n\n /**\n * Create nodemailer transporter based on configuration\n */\n private static async createTransporter(\n config: MailConfig\n ): Promise<MailTransporter> {\n switch (config.default) {\n case \"smtp\":\n return this.createSMTPTransporter(config.smtp!);\n\n case \"sendgrid\":\n return this.createSendGridTransporter(config.sendgrid!);\n\n case \"mailgun\":\n return this.createMailgunTransporter(config.mailgun!);\n\n case \"ses\":\n return this.createSESTransporter(config.ses!);\n\n case \"log\":\n return this.createLogTransporter();\n\n default:\n throw new Error(`Unsupported mail driver: ${config.default}`);\n }\n }\n\n /**\n * Create SMTP transporter\n */\n private static createSMTPTransporter(config: SMTPConfig): MailTransporter {\n return nodemailer.createTransport({\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.auth,\n tls: config.tls,\n });\n }\n\n /**\n * Create SendGrid transporter\n */\n private static createSendGridTransporter(\n config: SendGridConfig\n ): MailTransporter {\n return nodemailer.createTransport({\n host: \"smtp.sendgrid.net\",\n port: 587,\n auth: {\n user: \"apikey\",\n pass: config.apiKey,\n },\n });\n }\n\n /**\n * Create Mailgun transporter\n */\n private static createMailgunTransporter(\n config: MailgunConfig\n ): MailTransporter {\n const nodemailerMailgun = require(\"nodemailer-mailgun-transport\");\n return nodemailer.createTransport(\n nodemailerMailgun({\n auth: {\n api_key: config.apiKey,\n domain: config.domain,\n },\n host: config.host || \"api.mailgun.net\",\n })\n );\n }\n\n /**\n * Create AWS SES transporter\n */\n private static createSESTransporter(config: SESConfig): MailTransporter {\n const { SESClient, SendRawEmailCommand } = require(\"@aws-sdk/client-ses\");\n\n const clientConfig: Record<string, unknown> = {\n region: config.region,\n };\n\n if (config.accessKeyId && config.secretAccessKey) {\n clientConfig.credentials = {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n sessionToken: config.sessionToken,\n };\n }\n\n const ses = new SESClient(clientConfig);\n\n const transporterOptions = {\n SES: {\n ses,\n aws: { SendRawEmailCommand },\n },\n };\n\n return nodemailer.createTransport(transporterOptions as any);\n }\n\n /**\n * Create log-only transporter (for testing)\n */\n private static createLogTransporter(): MailTransporter {\n return nodemailer.createTransport({\n streamTransport: true,\n newline: \"unix\",\n buffer: true,\n });\n }\n\n /**\n * Send an email immediately\n */\n static async send(mailable: Mailable | MailMessage): Promise<void> {\n if (!this.transporter || !this.config) {\n throw new Error(\n \"MailService not initialized. Call MailService.init() first.\"\n );\n }\n\n let message: MailMessage;\n\n if (mailable instanceof Mailable) {\n const { message: msg, viewName, viewData } = mailable.getMessage();\n\n // Render template if view is specified\n if (viewName && this.config.templates) {\n const { html, text } = await TemplateRenderer.render(\n viewName,\n viewData\n );\n msg.html = html;\n msg.text = text;\n }\n\n message = msg as MailMessage;\n } else {\n message = mailable;\n }\n\n // Apply default from address if not specified\n if (!message.from && this.config.from) {\n message.from = this.config.from;\n }\n\n // Apply default reply-to if not specified\n if (!message.replyTo && this.config.replyTo) {\n message.replyTo = this.config.replyTo.address;\n }\n\n // Convert from object to string format\n const mailOptions = {\n ...message,\n from: message.from\n ? typeof message.from === \"string\"\n ? message.from\n : message.from.name\n ? `\"${message.from.name}\" <${message.from.address}>`\n : message.from.address\n : undefined,\n };\n\n try {\n const info = await this.transporter.sendMail(mailOptions);\n\n if (this.config.default === \"log\") {\n console.log(\"Email preview:\");\n console.log(\"To:\", message.to);\n console.log(\"Subject:\", message.subject);\n console.log(\"---\");\n } else {\n console.log(`Email sent: ${info.messageId}`);\n }\n } catch (error) {\n console.error(\"Failed to send email:\", error);\n throw error;\n }\n }\n\n /**\n * Queue an email for async sending\n */\n static async queue(mailable: Mailable): Promise<void> {\n if (!this.config?.queue?.enabled) {\n // If queue is not enabled, send immediately\n return this.send(mailable);\n }\n\n await MailQueue.add(mailable);\n }\n\n /**\n * Send a raw email message\n */\n static async sendRaw(message: MailMessage): Promise<void> {\n return this.send(message);\n }\n\n /**\n * Get the mail configuration\n */\n static getConfig(): MailConfig | undefined {\n return this.config;\n }\n\n /**\n * Verify transporter connection\n */\n static async verify(): Promise<boolean> {\n if (!this.transporter) {\n throw new Error(\"MailService not initialized\");\n }\n\n try {\n await this.transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Mail transporter verification failed:\", error);\n return false;\n }\n }\n}\n","import { Mailable } from \"../Mailable\";\nimport { MailQueueConfig } from \"../types\";\n\n/**\n * Queue job for email sending\n */\ninterface MailJob {\n id: string;\n mailable: Mailable;\n attempts: number;\n createdAt: Date;\n nextRetry?: Date;\n}\n\n/**\n * Mail queue for async email processing\n */\nexport class MailQueue {\n private static config?: MailQueueConfig;\n private static queue: MailJob[] = [];\n private static processing = false;\n private static redisClient?: any;\n\n /**\n * Initialize the mail queue\n */\n static async init(config: MailQueueConfig) {\n this.config = config;\n\n if (config.driver === \"redis\" && config.redis) {\n await this.initRedis(config.redis);\n }\n\n // Start processing queue\n this.startProcessing();\n }\n\n /**\n * Initialize Redis connection\n */\n private static async initRedis(\n redisConfig: NonNullable<MailQueueConfig[\"redis\"]>\n ) {\n try {\n const Redis = require(\"ioredis\");\n this.redisClient = new Redis({\n host: redisConfig.host,\n port: redisConfig.port,\n password: redisConfig.password,\n db: redisConfig.db || 0,\n });\n\n this.redisClient.on(\"error\", (err: Error) => {\n console.error(\"Redis connection error:\", err);\n });\n } catch (error) {\n console.warn(\"Redis not available, falling back to memory queue\");\n this.config!.driver = \"memory\";\n }\n }\n\n /**\n * Add a job to the queue\n */\n static async add(mailable: Mailable): Promise<void> {\n const job: MailJob = {\n id: this.generateId(),\n mailable,\n attempts: 0,\n createdAt: new Date(),\n };\n\n if (this.config?.driver === \"redis\" && this.redisClient) {\n await this.redisClient.lpush(\"mail:queue\", JSON.stringify(job));\n } else {\n this.queue.push(job);\n }\n }\n\n /**\n * Start processing the queue\n */\n private static startProcessing() {\n if (this.processing) return;\n this.processing = true;\n\n setInterval(async () => {\n await this.processNext();\n }, 1000);\n }\n\n /**\n * Process next job in queue\n */\n private static async processNext() {\n let job: MailJob | null = null;\n\n if (this.config?.driver === \"redis\" && this.redisClient) {\n const data = await this.redisClient.rpop(\"mail:queue\");\n if (data) {\n job = JSON.parse(data);\n }\n } else {\n job = this.queue.shift() || null;\n }\n\n if (!job) return;\n\n // Check if we should retry\n if (job.nextRetry && new Date() < job.nextRetry) {\n await this.add(job.mailable);\n return;\n }\n\n try {\n await job.mailable.send();\n } catch (error) {\n await this.handleFailedJob(job, error as Error);\n }\n }\n\n /**\n * Handle failed job\n */\n private static async handleFailedJob(job: MailJob, error: Error) {\n const maxRetries = this.config?.retries || 3;\n job.attempts++;\n\n if (job.attempts < maxRetries) {\n // Calculate exponential backoff\n const delay =\n (this.config?.retryDelay || 60) * Math.pow(2, job.attempts - 1);\n job.nextRetry = new Date(Date.now() + delay * 1000);\n\n console.warn(\n `Mail job ${job.id} failed (attempt ${job.attempts}/${maxRetries}), retrying in ${delay}s`\n );\n\n await this.add(job.mailable);\n } else {\n console.error(\n `Mail job ${job.id} failed after ${maxRetries} attempts:`,\n error\n );\n await this.storeFailedJob(job, error);\n }\n }\n\n /**\n * Store failed job for manual review\n */\n private static async storeFailedJob(job: MailJob, error: Error) {\n const failedJob = {\n ...job,\n error: error.message,\n failedAt: new Date(),\n };\n\n if (this.config?.driver === \"redis\" && this.redisClient) {\n await this.redisClient.lpush(\"mail:failed\", JSON.stringify(failedJob));\n } else {\n // In memory, just log it\n console.error(\"Failed mail job:\", failedJob);\n }\n }\n\n /**\n * Generate unique job ID\n */\n private static generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Get queue size\n */\n static async size(): Promise<number> {\n if (this.config?.driver === \"redis\" && this.redisClient) {\n return await this.redisClient.llen(\"mail:queue\");\n }\n return this.queue.length;\n }\n\n /**\n * Clear the queue\n */\n static async clear(): Promise<void> {\n if (this.config?.driver === \"redis\" && this.redisClient) {\n await this.redisClient.del(\"mail:queue\");\n } else {\n this.queue = [];\n }\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import ArcanaJSServer from \"../ArcanaJSServer\";\n\nexport abstract class ServiceProvider {\n protected app: ArcanaJSServer;\n\n constructor(app: ArcanaJSServer) {\n this.app = app;\n }\n\n /**\n * Register any application services.\n */\n register(): void {\n //\n }\n\n /**\n * Bootstrap any application services.\n */\n boot(): void {\n //\n }\n\n /**\n * Shutdown any application services.\n */\n async shutdown(): Promise<void> {\n //\n }\n}\n","import { ServiceProvider } from \"../server/support/ServiceProvider\";\nimport { MailService } from \"./MailService\";\nimport { MailConfig } from \"./types\";\n\n/**\n * Mail Service Provider\n *\n * Registers and bootstraps the mail system\n */\nexport class MailProvider extends ServiceProvider {\n async register() {\n console.log(\"⚙️ MailProvider: Initializing...\");\n\n // Get config from container (loaded by ArcanaJSServer)\n let mailConfig: MailConfig | undefined;\n\n try {\n mailConfig = this.app.container.resolve<MailConfig>(\"MailConfig\");\n console.log(\"✓ MailProvider: Configuration loaded successfully\");\n } catch (err) {\n console.warn(\"⚠ MailProvider: No configuration found - Skipping setup\");\n return;\n }\n\n try {\n // Initialize Mail Service\n await MailService.init(mailConfig);\n console.log(\n `✓ MailProvider: Service initialized with driver '${mailConfig.default}'`\n );\n\n // Register in container\n this.app.container.singleton(\"MailConfig\", () => mailConfig!);\n this.app.container.singleton(\"MailService\", () => MailService);\n\n console.log(\"✅ MailProvider: Ready\");\n } catch (error) {\n console.error(\"✗ MailProvider: Initialization failed\", error);\n throw error;\n }\n }\n\n async boot() {\n try {\n const config = this.app.container.resolve<MailConfig>(\"MailConfig\");\n\n // Verify mail connection if not using log driver\n if (config && config.default !== \"log\") {\n console.log(\"⚙️ MailProvider: Verifying transporter connection...\");\n const verified = await MailService.verify();\n if (verified) {\n console.log(\"✓ MailProvider: Transporter verified successfully\");\n }\n }\n } catch (error) {\n console.warn(\"⚠ MailProvider: Transporter verification failed\", error);\n }\n }\n}\n"],"names":["module","exports","require","Mailable","message","to","address","name","this","from","subject","view","template","data","viewName","viewData","html","content","text","cc","bcc","replyTo","attach","attachment","attachments","push","attachFromPath","path","filename","split","pop","attachData","contentType","priority","level","withHeaders","headers","getMessage","build","send","MailService","queue","TemplateRenderer","init","config","render","templateName","Error","templatePath","process","cwd","viewsPath","engine","fs","renderEJS","renderHandlebars","defaultLayout","layoutsPath","applyLayout","htmlToText","ejs","Handlebars","compile","compiled","_this$config","layoutPath","layoutData","body","replace","trim","_config$queue","transporter","createTransporter","templates","enabled","MailQueue","default","createSMTPTransporter","smtp","createSendGridTransporter","sendgrid","createMailgunTransporter","mailgun","createSESTransporter","ses","createLogTransporter","nodemailer","host","port","secure","auth","tls","user","pass","apiKey","nodemailerMailgun","api_key","domain","SESClient","SendRawEmailCommand","clientConfig","region","accessKeyId","secretAccessKey","credentials","sessionToken","transporterOptions","SES","aws","streamTransport","newline","buffer","mailable","msg","mailOptions","undefined","info","sendMail","console","log","messageId","error","add","sendRaw","getConfig","verify","driver","redis","initRedis","startProcessing","redisConfig","Redis","redisClient","password","db","on","err","warn","job","id","generateId","attempts","createdAt","Date","lpush","JSON","stringify","processing","setInterval","async","processNext","_this$config2","rpop","parse","shift","nextRetry","handleFailedJob","_this$config3","maxRetries","retries","_this$config4","delay","retryDelay","Math","pow","now","storeFailedJob","_this$config5","failedJob","failedAt","random","toString","substr","size","_this$config6","llen","length","clear","_this$config7","del","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","ServiceProvider","constructor","app","register","boot","shutdown","MailProvider","mailConfig","container","resolve","singleton"],"ignoreList":[],"sourceRoot":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(()=>{"use strict";var t,e={},s={};function r(t){var a=s[t];if(void 0!==a)return a.exports;var i=s[t]={exports:{}};return e[t](i,i.exports,r),i.exports}r.m=e,r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var s in e)r.o(e,s)&&!r.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},r.f={},r.e=t=>Promise.all(Object.keys(r.f).reduce((e,s)=>(r.f[s](t,e),e),[])),r.u=t=>t+".js",r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},t={960:1},r.f.require=(e,s)=>{if(!t[e]){var a=require("./"+r.u(e));t[e]||(e=>{var s=e.modules,a=e.ids,i=e.runtime;for(var o in s)r.o(s,o)&&(r.m[o]=s[o]);i&&i(r);for(var n=0;n<a.length;n++)t[a[n]]=1})(a)}};var a={};r.r(a),r.d(a,{FormRequest:()=>u,JsonResource:()=>h,ValidationException:()=>n,Validator:()=>l});class i{static macros={};static macro(t,e){this.macros[t]=e,this.prototype[t]=e}static mixin(t){Object.keys(t).forEach(e=>{this.macro(e,t[e])})}static hasMacro(t){return!!this.macros[t]}}class o extends i{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(t,e){super(),this.tableName=t,this.adapter=e}select(...t){return this.selectColumns=t,this}where(t,e,s){return void 0===s&&(s=e,e="="),this.whereClauses.push({column:t,operator:e,value:s,boolean:"AND"}),this}orWhere(t,e,s){return void 0===s&&(s=e,e="="),this.whereClauses.push({column:t,operator:e,value:s,boolean:"OR"}),this}whereIn(t,e){return this.whereClauses.push({column:t,operator:"IN",value:e,boolean:"AND"}),this}whereNotIn(t,e){return this.whereClauses.push({column:t,operator:"NOT IN",value:e,boolean:"AND"}),this}whereBetween(t,e){return this.whereClauses.push({column:t,operator:"BETWEEN",value:e,boolean:"AND"}),this}whereNull(t){return this.whereClauses.push({column:t,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(t){return this.whereClauses.push({column:t,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(t,e="ASC"){return this.orderByClauses.push({column:t,direction:e.toUpperCase()}),this}limit(t){return this.limitValue=t,this}offset(t){return this.offsetValue=t,this}join(t,e,s,r,a="INNER"){return this.joinClauses.push({type:a,table:t,first:e,operator:s,second:r}),this}leftJoin(t,e,s,r){return this.join(t,e,s,r,"LEFT")}rightJoin(t,e,s,r){return this.join(t,e,s,r,"RIGHT")}eagerLoads=[];setModel(t){return this.model=t,this}with(t){return Array.isArray(t)?this.eagerLoads.push(...t):this.eagerLoads.push(t),this}async get(){const t={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},e=await this.adapter.select(this.tableName,t);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(e):e}async eagerLoadRelations(t){if(0===t.length)return t;const e=t.map(t=>this.model.hydrate(t));for(const t of this.eagerLoads){const s=new this.model;if("function"!=typeof s[t])throw new Error(`Relation ${t} does not exist on ${this.model.name}`);const r=s[t]();r.addEagerConstraints(e);const a=await r.get();r.match(e,a,t)}return e}async first(){return this.limit(1),(await this.get())[0]||null}async find(t){return this.where("id",t).first()}async count(){this.selectColumns=["COUNT(*) as count"];const t=await this.first();return t?t.count:0}async pluck(t){return this.select(t),(await this.get()).map(e=>e[t])}async sum(t){this.selectColumns=[`SUM(${t}) as sum`];const e=await this.first();return e&&e.sum||0}async avg(t){this.selectColumns=[`AVG(${t}) as avg`];const e=await this.first();return e&&e.avg||0}async min(t){this.selectColumns=[`MIN(${t}) as min`];const e=await this.first();return e?e.min:null}async max(t){this.selectColumns=[`MAX(${t}) as max`];const e=await this.first();return e?e.max:null}async exists(){return await this.count()>0}async paginate(t=1,e=15){const s=await this.count(),r=(t-1)*e;return this.limit(e).offset(r),{data:await this.get(),total:s,perPage:e,currentPage:t,lastPage:Math.ceil(s/e)}}clone(){const t=new o(this.tableName,this.adapter);return t.selectColumns=[...this.selectColumns],t.whereClauses=[...this.whereClauses],t.orderByClauses=[...this.orderByClauses],t.joinClauses=[...this.joinClauses],t.limitValue=this.limitValue,t.offsetValue=this.offsetValue,t}}class n extends Error{constructor(t){super("The given data was invalid."),this.name="ValidationException",this.errors=t,this.status=422}}class l{errors={};static customValidators={};static registerValidator(t,e){l.customValidators[t]=e}constructor(t,e){this.data=t,this.rules=e}static make(t,e){return new l(t,e)}setDatabaseAdapter(t){return this.databaseAdapter=t,this}async fails(){return await this.validateRules(),Object.keys(this.errors).length>0}async passes(){return!await this.fails()}errors_(){return this.errors}async validate(){const t=await this.validateRules();if(Object.keys(this.errors).length>0)throw new n(this.errors);return t}async validateRules(){this.errors={};const t={};!this.databaseAdapter&&this.needsDatabaseAdapter()&&await this.autoInjectDatabaseAdapter();for(const[e,s]of Object.entries(this.rules)){const r=s.split("|"),a=this.getValue(e);for(const t of r)await this.applyRule(e,a,t);void 0!==a&&(t[e]=a)}return t}needsDatabaseAdapter(){for(const t of Object.values(this.rules)){const e=t.split("|");for(const t of e){const e=t.split(":")[0];if("unique"===e||"exists"===e)return!0}}return!1}async autoInjectDatabaseAdapter(){try{const{Container:t}=await Promise.all([r.e(630),r.e(529)]).then(r.bind(r,529)),e=t.getInstance();this.databaseAdapter=await e.make("DatabaseAdapter")}catch(t){throw new Error("Database adapter not available. Ensure DatabaseProvider is registered in your application.")}}getValue(t){return t.split(".").reduce((t,e)=>null==t?void 0:t[e],this.data)}async applyRule(t,e,s){const[r,...a]=s.split(":"),i=a.join(":");if(!this.isEmpty(e)||"required"===r)switch(r){case"required":this.isEmpty(e)&&this.addError(t,`${t} is required.`);break;case"string":"string"!=typeof e&&this.addError(t,`${t} must be a string.`);break;case"numeric":isNaN(Number(e))&&this.addError(t,`${t} must be a number.`);break;case"integer":Number.isInteger(Number(e))||this.addError(t,`${t} must be an integer.`);break;case"float":isNaN(parseFloat(e))&&this.addError(t,`${t} must be a float.`);break;case"boolean":"boolean"!=typeof e&&"true"!==e&&"false"!==e&&0!==e&&1!==e&&this.addError(t,`${t} must be a boolean.`);break;case"array":Array.isArray(e)?i&&await this.validateArrayContent(t,e,i):this.addError(t,`${t} must be an array.`);break;case"object":("object"!=typeof e||null===e||Array.isArray(e))&&this.addError(t,`${t} must be an object.`);break;case"json":this.isValidJson(e)||this.addError(t,`${t} must be a valid JSON string.`);break;case"email":/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(e))||this.addError(t,`${t} must be a valid email address.`);break;case"url":try{new URL(e)}catch{this.addError(t,`${t} must be a valid URL.`)}break;case"alpha":/^[a-zA-Z]+$/.test(e)||this.addError(t,`${t} must contain only letters.`);break;case"alpha_num":/^[a-zA-Z0-9]+$/.test(e)||this.addError(t,`${t} must contain only letters and numbers.`);break;case"min":this.validateMin(t,e,i);break;case"max":this.validateMax(t,e,i);break;case"in":i.split(",").includes(String(e))||this.addError(t,`${t} is invalid.`);break;case"not_in":i.split(",").includes(String(e))&&this.addError(t,`${t} is invalid.`);break;case"same":e!==this.getValue(i)&&this.addError(t,`${t} must match ${i}.`);break;case"date":isNaN(Date.parse(e))&&this.addError(t,`${t} must be a valid date.`);break;case"unique":await this.validateUnique(t,e,i);break;case"exists":await this.validateExists(t,e,i);break;default:const s=l.customValidators[r];if(s){const a=await s(e,this.data,i);!0!==a&&this.addError(t,"string"==typeof a?a:`${t} validation failed for ${r}.`)}}}async validateArrayContent(t,e,s){for(let r=0;r<e.length;r++){const a=e[r],i=`${t}.${r}`;await this.applyRule(i,a,s)}}validateMin(t,e,s){const r=parseFloat(s);"string"==typeof e&&e.length<r?this.addError(t,`${t} must be at least ${r} characters.`):"number"==typeof e&&e<r?this.addError(t,`${t} must be at least ${r}.`):Array.isArray(e)&&e.length<r&&this.addError(t,`${t} must have at least ${r} items.`)}validateMax(t,e,s){const r=parseFloat(s);"string"==typeof e&&e.length>r?this.addError(t,`${t} must not be greater than ${r} characters.`):"number"==typeof e&&e>r?this.addError(t,`${t} must not be greater than ${r}.`):Array.isArray(e)&&e.length>r&&this.addError(t,`${t} must not have more than ${r} items.`)}isValidJson(t){if("string"!=typeof t)return!1;try{return JSON.parse(t),!0}catch{return!1}}isEmpty(t){return null==t||""===t}async validateUnique(t,e,s){if(!this.databaseAdapter)throw new Error("Database adapter not set. Use setDatabaseAdapter() before using unique rule.");const r=s.split(","),a=r[0],i=r[1]||t,n=r[2],l=r[3]||"id";if(!a)throw new Error(`Invalid unique rule format for ${t}`);const u=new o(a,this.databaseAdapter);u.where(i,e),n&&u.where(l,"!=",n),await u.count()>0&&this.addError(t,`The ${t} has already been taken.`)}async validateExists(t,e,s){if(!this.databaseAdapter)throw new Error("Database adapter not set. Use setDatabaseAdapter() before using exists rule.");const r=s.split(","),a=r[0],i=r[1]||"id";if(!a)throw new Error(`Invalid exists rule format for ${t}`);const n=new o(a,this.databaseAdapter);n.where(i,e),await n.exists()||this.addError(t,`The selected ${t} is invalid.`)}addError(t,e){this.errors[t]||(this.errors[t]=[]),this.errors[t].push(e)}}class u{constructor(t){this.req=t}authorize(){return!0}async validate(){if(!this.authorize())throw new Error("This action is unauthorized.");return l.make(this.req.body,this.rules()).validate()}input(t,e=null){return this.req.body[t]||e}all(){return this.req.body}}class h{constructor(t){this.resource=t}static make(t){return new this(t)}static collection(t){return new c(t,this)}resolve(t){return null===this.resource?null:Array.isArray(this.resource)?this.resource.map(e=>new this.constructor(e).toArray(t)):this.toArray(t)}toArray(t){return this.resource&&"function"==typeof this.resource.toJSON?this.resource.toJSON():this.resource}}class c extends h{constructor(t,e){super(t),this.collects=e}resolve(t){return this.resource.map(e=>new this.collects(e).resolve(t))}}var d=exports;for(var m in a)d[m]=a[m];a.__esModule&&Object.defineProperty(d,"__esModule",{value:!0})})();
|
|
2
|
+
//# sourceMappingURL=arcanajs.validator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"arcanajs.validator.js","mappings":"uBAIIA,E,KCHAC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaE,QAGrB,IAAIC,EAASN,EAAyBE,GAAY,CAGjDG,QAAS,CAAC,GAOX,OAHAE,EAAoBL,GAAUI,EAAQA,EAAOD,QAASJ,GAG/CK,EAAOD,OACf,CAGAJ,EAAoBO,EAAID,ECxBxBN,EAAoBQ,EAAKH,IACxB,IAAII,EAASJ,GAAUA,EAAOK,WAC7B,IAAOL,EAAiB,QACxB,IAAM,EAEP,OADAL,EAAoBW,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,GCLRT,EAAoBW,EAAI,CAACP,EAASS,KACjC,IAAI,IAAIC,KAAOD,EACXb,EAAoBe,EAAEF,EAAYC,KAASd,EAAoBe,EAAEX,EAASU,IAC5EE,OAAOC,eAAeb,EAASU,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3Ed,EAAoBoB,EAAI,CAAC,EAGzBpB,EAAoBqB,EAAKC,GACjBC,QAAQC,IAAIR,OAAOS,KAAKzB,EAAoBoB,GAAGM,OAAO,CAACC,EAAUb,KACvEd,EAAoBoB,EAAEN,GAAKQ,EAASK,GAC7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AAKiK,SAAWA,CAClB,CAEAJ,OAAAA,CAAQC,GACN,OAAO9J,KAAK0J,SAASlG,IAAKmF,GACP,IAAI3I,KAAKiK,SAAStB,GACnBkB,QAAQC,GAE5B,E","sources":["webpack://arcanajs/webpack/runtime/require chunk loading","webpack://arcanajs/webpack/bootstrap","webpack://arcanajs/webpack/runtime/compat get default export","webpack://arcanajs/webpack/runtime/define property getters","webpack://arcanajs/webpack/runtime/ensure chunk","webpack://arcanajs/webpack/runtime/get javascript chunk filename","webpack://arcanajs/webpack/runtime/hasOwnProperty shorthand","webpack://arcanajs/webpack/runtime/make namespace object","webpack://arcanajs/./src/lib/arcanox/support/Macroable.ts","webpack://arcanajs/./src/lib/arcanox/QueryBuilder.ts","webpack://arcanajs/./src/lib/validation/ValidationException.ts","webpack://arcanajs/./src/lib/validation/Validator.ts","webpack://arcanajs/./src/lib/server/http/FormRequest.ts","webpack://arcanajs/./src/lib/server/http/JsonResource.ts"],"sourcesContent":["// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"loaded\", otherwise not loaded yet\nvar installedChunks = {\n\t960: 1\n};\n\n// no on chunks loaded\n\nvar installChunk = (chunk) => {\n\tvar moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\tfor(var i = 0; i < chunkIds.length; i++)\n\t\tinstalledChunks[chunkIds[i]] = 1;\n\n};\n\n// require() chunk loading for javascript\n__webpack_require__.f.require = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\tvar installedChunk = require(\"./\" + __webpack_require__.u(chunkId));\n\t\t\tif (!installedChunks[chunkId]) {\n\t\t\t\tinstallChunk(installedChunk);\n\t\t\t}\n\t\t} else installedChunks[chunkId] = 1;\n\t}\n};\n\n// no external install chunk\n\n// no HMR\n\n// no HMR manifest","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".js\";\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Macroable trait\n * Allows adding custom methods to a class at runtime\n */\nexport class Macroable {\n protected static macros: Record<string, Function> = {};\n\n /**\n * Register a custom macro\n */\n static macro(name: string, macro: Function): void {\n this.macros[name] = macro;\n (this.prototype as any)[name] = macro;\n }\n\n /**\n * Mix another object into the class\n */\n static mixin(mixin: Record<string, Function>): void {\n Object.keys(mixin).forEach((key) => {\n this.macro(key, mixin[key]);\n });\n }\n\n /**\n * Check if macro exists\n */\n static hasMacro(name: string): boolean {\n return !!this.macros[name];\n }\n}\n","import type {\n JoinClause,\n OrderByClause,\n SelectOptions,\n WhereClause,\n} from \"./types\";\n\nimport { Macroable } from \"./support/Macroable\";\n\n/**\n * Query Builder - Fluent interface for building database queries\n * Arcanox Query Builder\n */\nexport class QueryBuilder<T = any> extends Macroable {\n protected tableName: string;\n protected selectColumns: string[] = [\"*\"];\n protected whereClauses: WhereClause[] = [];\n protected orderByClauses: OrderByClause[] = [];\n protected joinClauses: JoinClause[] = [];\n protected limitValue?: number;\n protected offsetValue?: number;\n protected adapter: any; // DatabaseAdapter\n\n constructor(table: string, adapter: any) {\n super();\n this.tableName = table;\n this.adapter = adapter;\n }\n\n /**\n * Select specific columns\n */\n select(...columns: string[]): this {\n this.selectColumns = columns;\n return this;\n }\n\n /**\n * Add a WHERE clause\n */\n where(column: string, operator: any, value?: any): this {\n // Support where(column, value) syntax\n if (value === undefined) {\n value = operator;\n operator = \"=\";\n }\n\n this.whereClauses.push({\n column,\n operator,\n value,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * Add an OR WHERE clause\n */\n orWhere(column: string, operator: any, value?: any): this {\n if (value === undefined) {\n value = operator;\n operator = \"=\";\n }\n\n this.whereClauses.push({\n column,\n operator,\n value,\n boolean: \"OR\",\n });\n return this;\n }\n\n /**\n * WHERE IN clause\n */\n whereIn(column: string, values: any[]): this {\n this.whereClauses.push({\n column,\n operator: \"IN\",\n value: values,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * WHERE NOT IN clause\n */\n whereNotIn(column: string, values: any[]): this {\n this.whereClauses.push({\n column,\n operator: \"NOT IN\",\n value: values,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * WHERE BETWEEN clause\n */\n whereBetween(column: string, range: [any, any]): this {\n this.whereClauses.push({\n column,\n operator: \"BETWEEN\",\n value: range,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * WHERE NULL clause\n */\n whereNull(column: string): this {\n this.whereClauses.push({\n column,\n operator: \"IS NULL\",\n value: null,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * WHERE NOT NULL clause\n */\n whereNotNull(column: string): this {\n this.whereClauses.push({\n column,\n operator: \"IS NOT NULL\",\n value: null,\n boolean: \"AND\",\n });\n return this;\n }\n\n /**\n * Add ORDER BY clause\n */\n orderBy(\n column: string,\n direction: \"ASC\" | \"DESC\" | \"asc\" | \"desc\" = \"ASC\"\n ): this {\n this.orderByClauses.push({\n column,\n direction: direction.toUpperCase() as \"ASC\" | \"DESC\",\n });\n return this;\n }\n\n /**\n * Add LIMIT clause\n */\n limit(count: number): this {\n this.limitValue = count;\n return this;\n }\n\n /**\n * Add OFFSET clause\n */\n offset(count: number): this {\n this.offsetValue = count;\n return this;\n }\n\n /**\n * Add JOIN clause\n */\n join(\n table: string,\n first: string,\n operator: string,\n second: string,\n type: \"INNER\" | \"LEFT\" | \"RIGHT\" = \"INNER\"\n ): this {\n this.joinClauses.push({\n type,\n table,\n first,\n operator,\n second,\n });\n return this;\n }\n\n /**\n * Add LEFT JOIN clause\n */\n leftJoin(\n table: string,\n first: string,\n operator: string,\n second: string\n ): this {\n return this.join(table, first, operator, second, \"LEFT\");\n }\n\n /**\n * Add RIGHT JOIN clause\n */\n rightJoin(\n table: string,\n first: string,\n operator: string,\n second: string\n ): this {\n return this.join(table, first, operator, second, \"RIGHT\");\n }\n\n protected eagerLoads: string[] = [];\n protected model: any; // Model class\n\n /**\n * Set the model class\n */\n setModel(model: any): this {\n this.model = model;\n return this;\n }\n\n /**\n * Eager load relationships\n */\n with(relations: string | string[]): this {\n if (Array.isArray(relations)) {\n this.eagerLoads.push(...relations);\n } else {\n this.eagerLoads.push(relations);\n }\n return this;\n }\n\n /**\n * Execute query and get all results\n */\n async get(): Promise<T[]> {\n const options: SelectOptions = {\n columns: this.selectColumns,\n where: this.whereClauses,\n orderBy: this.orderByClauses,\n limit: this.limitValue,\n offset: this.offsetValue,\n joins: this.joinClauses,\n };\n\n const results = await this.adapter.select(this.tableName, options);\n\n if (this.eagerLoads.length > 0 && this.model) {\n return await this.eagerLoadRelations(results);\n }\n\n return results;\n }\n\n /**\n * Eager load relations\n */\n protected async eagerLoadRelations(results: any[]): Promise<any[]> {\n if (results.length === 0) return results;\n\n // Hydrate models first\n const models = results.map((result) => this.model.hydrate(result));\n\n for (const relationName of this.eagerLoads) {\n // Check if relation exists on model\n const instance = new this.model();\n if (typeof instance[relationName] !== \"function\") {\n throw new Error(\n `Relation ${relationName} does not exist on ${this.model.name}`\n );\n }\n\n // Get relation instance\n const relation = instance[relationName]();\n\n // Add constraints for eager loading\n relation.addEagerConstraints(models);\n\n // Get related results\n const relatedResults = await relation.get();\n\n // Match results to models\n relation.match(models, relatedResults, relationName);\n }\n\n return models;\n }\n\n /**\n * Get first result\n */\n async first(): Promise<T | null> {\n this.limit(1);\n const results = await this.get();\n return results[0] || null;\n }\n\n /**\n * Find by ID\n */\n async find(id: any): Promise<T | null> {\n return this.where(\"id\", id).first();\n }\n\n /**\n * Count results\n */\n async count(): Promise<number> {\n this.selectColumns = [\"COUNT(*) as count\"];\n const result = await this.first();\n return result ? (result as any).count : 0;\n }\n\n /**\n * Get specific column values\n */\n async pluck(column: string): Promise<any[]> {\n this.select(column);\n const results = await this.get();\n return results.map((row) => (row as any)[column]);\n }\n\n /**\n * Sum of column\n */\n async sum(column: string): Promise<number> {\n this.selectColumns = [`SUM(${column}) as sum`];\n const result = await this.first();\n return result ? (result as any).sum || 0 : 0;\n }\n\n /**\n * Average of column\n */\n async avg(column: string): Promise<number> {\n this.selectColumns = [`AVG(${column}) as avg`];\n const result = await this.first();\n return result ? (result as any).avg || 0 : 0;\n }\n\n /**\n * Minimum value of column\n */\n async min(column: string): Promise<any> {\n this.selectColumns = [`MIN(${column}) as min`];\n const result = await this.first();\n return result ? (result as any).min : null;\n }\n\n /**\n * Maximum value of column\n */\n async max(column: string): Promise<any> {\n this.selectColumns = [`MAX(${column}) as max`];\n const result = await this.first();\n return result ? (result as any).max : null;\n }\n\n /**\n * Check if any records exist\n */\n async exists(): Promise<boolean> {\n const count = await this.count();\n return count > 0;\n }\n\n /**\n * Paginate results\n */\n async paginate(\n page: number = 1,\n perPage: number = 15\n ): Promise<{\n data: T[];\n total: number;\n perPage: number;\n currentPage: number;\n lastPage: number;\n }> {\n const total = await this.count();\n const offset = (page - 1) * perPage;\n\n this.limit(perPage).offset(offset);\n const data = await this.get();\n\n return {\n data,\n total,\n perPage,\n currentPage: page,\n lastPage: Math.ceil(total / perPage),\n };\n }\n\n /**\n * Clone the query builder\n */\n clone(): QueryBuilder<T> {\n const cloned = new QueryBuilder<T>(this.tableName, this.adapter);\n cloned.selectColumns = [...this.selectColumns];\n cloned.whereClauses = [...this.whereClauses];\n cloned.orderByClauses = [...this.orderByClauses];\n cloned.joinClauses = [...this.joinClauses];\n cloned.limitValue = this.limitValue;\n cloned.offsetValue = this.offsetValue;\n return cloned;\n }\n}\n","export class ValidationException extends Error {\n public errors: Record<string, string[]>;\n public status: number;\n\n constructor(errors: Record<string, string[]>) {\n super(\"The given data was invalid.\");\n this.name = \"ValidationException\";\n this.errors = errors;\n this.status = 422;\n }\n}\n","import { QueryBuilder } from \"../arcanox/QueryBuilder\";\nimport type { DatabaseAdapter } from \"../arcanox/types\";\nimport { ValidationException } from \"./ValidationException\";\n\nexport class Validator {\n protected data: any;\n protected rules: Record<string, string>;\n protected errors: Record<string, string[]> = {};\n protected databaseAdapter?: DatabaseAdapter;\n\n /**\n * Map of custom validator functions.\n */\n private static customValidators: Record<\n string,\n (\n value: any,\n data: any,\n param?: string\n ) => true | string | Promise<true | string>\n > = {};\n\n /**\n * Register a custom validator.\n */\n public static registerValidator(\n name: string,\n fn: (\n value: any,\n data: any,\n param?: string\n ) => true | string | Promise<true | string>\n ): void {\n Validator.customValidators[name] = fn;\n }\n\n constructor(data: any, rules: Record<string, string>) {\n this.data = data;\n this.rules = rules;\n }\n\n static make(data: any, rules: Record<string, string>): Validator {\n return new Validator(data, rules);\n }\n\n /**\n * Set the database adapter for database validation rules\n */\n setDatabaseAdapter(adapter: DatabaseAdapter): this {\n this.databaseAdapter = adapter;\n return this;\n }\n\n async fails(): Promise<boolean> {\n await this.validateRules();\n return Object.keys(this.errors).length > 0;\n }\n\n async passes(): Promise<boolean> {\n return !(await this.fails());\n }\n\n errors_(): Record<string, string[]> {\n return this.errors;\n }\n\n async validate(): Promise<Record<string, any>> {\n const validated = await this.validateRules();\n\n if (Object.keys(this.errors).length > 0) {\n throw new ValidationException(this.errors);\n }\n\n return validated;\n }\n\n protected async validateRules(): Promise<Record<string, any>> {\n this.errors = {};\n const validated: Record<string, any> = {};\n\n // Auto-inject database adapter if needed and not already set\n if (!this.databaseAdapter && this.needsDatabaseAdapter()) {\n await this.autoInjectDatabaseAdapter();\n }\n\n for (const [field, ruleString] of Object.entries(this.rules)) {\n const rules = ruleString.split(\"|\");\n const value = this.getValue(field);\n\n for (const rule of rules) {\n await this.applyRule(field, value, rule);\n }\n\n if (value !== undefined) {\n validated[field] = value;\n }\n }\n\n return validated;\n }\n\n /**\n * Check if any rules require database adapter\n */\n protected needsDatabaseAdapter(): boolean {\n for (const ruleString of Object.values(this.rules)) {\n const rules = ruleString.split(\"|\");\n for (const rule of rules) {\n const ruleName = rule.split(\":\")[0];\n if (ruleName === \"unique\" || ruleName === \"exists\") {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Auto-inject database adapter from Container\n */\n protected async autoInjectDatabaseAdapter(): Promise<void> {\n try {\n // Dynamically import Container to avoid circular dependencies\n const { Container } = await import(\"../server/Container\");\n const container = Container.getInstance();\n this.databaseAdapter = await container.make(\"DatabaseAdapter\");\n } catch (error) {\n // If Container or DatabaseAdapter is not available, throw a helpful error\n throw new Error(\n \"Database adapter not available. Ensure DatabaseProvider is registered in your application.\"\n );\n }\n }\n\n protected getValue(field: string): any {\n return field.split(\".\").reduce((obj, key) => obj?.[key], this.data);\n }\n\n protected async applyRule(\n field: string,\n value: any,\n rule: string\n ): Promise<void> {\n const [ruleName, ...params] = rule.split(\":\");\n const param = params.join(\":\"); // Rejoin in case param contains colons\n\n // Skip validation if value is missing and rule is not 'required'\n if (this.isEmpty(value) && ruleName !== \"required\") {\n return;\n }\n\n switch (ruleName) {\n case \"required\":\n if (this.isEmpty(value)) this.addError(field, `${field} is required.`);\n break;\n case \"string\":\n if (typeof value !== \"string\")\n this.addError(field, `${field} must be a string.`);\n break;\n case \"numeric\":\n if (isNaN(Number(value)))\n this.addError(field, `${field} must be a number.`);\n break;\n case \"integer\":\n if (!Number.isInteger(Number(value)))\n this.addError(field, `${field} must be an integer.`);\n break;\n case \"float\":\n if (isNaN(parseFloat(value)))\n this.addError(field, `${field} must be a float.`);\n break;\n case \"boolean\":\n if (\n typeof value !== \"boolean\" &&\n value !== \"true\" &&\n value !== \"false\" &&\n value !== 0 &&\n value !== 1\n ) {\n this.addError(field, `${field} must be a boolean.`);\n }\n break;\n case \"array\":\n if (!Array.isArray(value)) {\n this.addError(field, `${field} must be an array.`);\n } else if (param) {\n // Handle array:type (e.g., array:string, array:object)\n await this.validateArrayContent(field, value, param);\n }\n break;\n case \"object\":\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value)\n ) {\n this.addError(field, `${field} must be an object.`);\n }\n break;\n case \"json\":\n if (!this.isValidJson(value))\n this.addError(field, `${field} must be a valid JSON string.`);\n break;\n case \"email\":\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(String(value)))\n this.addError(field, `${field} must be a valid email address.`);\n break;\n case \"url\":\n try {\n new URL(value);\n } catch {\n this.addError(field, `${field} must be a valid URL.`);\n }\n break;\n case \"alpha\":\n if (!/^[a-zA-Z]+$/.test(value))\n this.addError(field, `${field} must contain only letters.`);\n break;\n case \"alpha_num\":\n if (!/^[a-zA-Z0-9]+$/.test(value))\n this.addError(\n field,\n `${field} must contain only letters and numbers.`\n );\n break;\n case \"min\":\n this.validateMin(field, value, param);\n break;\n case \"max\":\n this.validateMax(field, value, param);\n break;\n case \"in\":\n const allowed = param.split(\",\");\n if (!allowed.includes(String(value)))\n this.addError(field, `${field} is invalid.`);\n break;\n case \"not_in\":\n const disallowed = param.split(\",\");\n if (disallowed.includes(String(value)))\n this.addError(field, `${field} is invalid.`);\n break;\n case \"same\":\n const otherValue = this.getValue(param);\n if (value !== otherValue)\n this.addError(field, `${field} must match ${param}.`);\n break;\n case \"date\":\n if (isNaN(Date.parse(value)))\n this.addError(field, `${field} must be a valid date.`);\n break;\n case \"unique\":\n await this.validateUnique(field, value, param);\n break;\n case \"exists\":\n await this.validateExists(field, value, param);\n break;\n default:\n // Custom validators\n const validatorFn = Validator.customValidators[ruleName];\n if (validatorFn) {\n const result = await validatorFn(value, this.data, param);\n if (result !== true) {\n this.addError(\n field,\n typeof result === \"string\"\n ? result\n : `${field} validation failed for ${ruleName}.`\n );\n }\n }\n break;\n }\n }\n\n protected async validateArrayContent(\n field: string,\n array: any[],\n type: string\n ): Promise<void> {\n for (let i = 0; i < array.length; i++) {\n const item = array[i];\n const itemField = `${field}.${i}`;\n\n // Recursively apply simple type checks\n // We construct a mini-rule for the item\n await this.applyRule(itemField, item, type);\n }\n }\n\n protected validateMin(field: string, value: any, param: string): void {\n const min = parseFloat(param);\n if (typeof value === \"string\" && value.length < min) {\n this.addError(field, `${field} must be at least ${min} characters.`);\n } else if (typeof value === \"number\" && value < min) {\n this.addError(field, `${field} must be at least ${min}.`);\n } else if (Array.isArray(value) && value.length < min) {\n this.addError(field, `${field} must have at least ${min} items.`);\n }\n }\n\n protected validateMax(field: string, value: any, param: string): void {\n const max = parseFloat(param);\n if (typeof value === \"string\" && value.length > max) {\n this.addError(\n field,\n `${field} must not be greater than ${max} characters.`\n );\n } else if (typeof value === \"number\" && value > max) {\n this.addError(field, `${field} must not be greater than ${max}.`);\n } else if (Array.isArray(value) && value.length > max) {\n this.addError(field, `${field} must not have more than ${max} items.`);\n }\n }\n\n protected isValidJson(value: any): boolean {\n if (typeof value !== \"string\") return false;\n try {\n JSON.parse(value);\n return true;\n } catch {\n return false;\n }\n }\n\n protected isEmpty(value: any): boolean {\n return value === undefined || value === null || value === \"\";\n }\n\n /**\n * Validate unique rule: unique:table,column,ignoreId,ignoreColumn\n * Examples:\n * - unique:users,email\n * - unique:users,email,5 (ignore record with id=5)\n * - unique:users,email,5,user_id (ignore record where user_id=5)\n */\n protected async validateUnique(\n field: string,\n value: any,\n param: string\n ): Promise<void> {\n if (!this.databaseAdapter) {\n throw new Error(\n \"Database adapter not set. Use setDatabaseAdapter() before using unique rule.\"\n );\n }\n\n const parts = param.split(\",\");\n const table = parts[0];\n const column = parts[1] || field;\n const ignoreId = parts[2];\n const ignoreColumn = parts[3] || \"id\";\n\n if (!table) {\n throw new Error(`Invalid unique rule format for ${field}`);\n }\n\n const query = new QueryBuilder(table, this.databaseAdapter);\n query.where(column, value);\n\n // Add ignore clause if provided\n if (ignoreId) {\n query.where(ignoreColumn, \"!=\", ignoreId);\n }\n\n const count = await query.count();\n\n if (count > 0) {\n this.addError(field, `The ${field} has already been taken.`);\n }\n }\n\n /**\n * Validate exists rule: exists:table,column\n * Example: exists:riads,id\n */\n protected async validateExists(\n field: string,\n value: any,\n param: string\n ): Promise<void> {\n if (!this.databaseAdapter) {\n throw new Error(\n \"Database adapter not set. Use setDatabaseAdapter() before using exists rule.\"\n );\n }\n\n const parts = param.split(\",\");\n const table = parts[0];\n const column = parts[1] || \"id\";\n\n if (!table) {\n throw new Error(`Invalid exists rule format for ${field}`);\n }\n\n const query = new QueryBuilder(table, this.databaseAdapter);\n query.where(column, value);\n\n const exists = await query.exists();\n\n if (!exists) {\n this.addError(field, `The selected ${field} is invalid.`);\n }\n }\n\n protected addError(field: string, message: string) {\n if (!this.errors[field]) {\n this.errors[field] = [];\n }\n this.errors[field].push(message);\n }\n}\n","import { Request } from \"express\";\nimport { Validator } from \"../../validation/Validator\";\n\nexport abstract class FormRequest {\n protected req: Request;\n\n constructor(req: Request) {\n this.req = req;\n }\n\n abstract rules(): Record<string, string>;\n\n authorize(): boolean {\n return true;\n }\n\n async validate(): Promise<Record<string, any>> {\n if (!this.authorize()) {\n throw new Error(\"This action is unauthorized.\");\n }\n\n const validator = Validator.make(this.req.body, this.rules());\n\n // This will throw ValidationException if fails\n return validator.validate();\n }\n\n // Helper to access request data\n input(key: string, defaultValue: any = null): any {\n return this.req.body[key] || defaultValue;\n }\n\n all(): any {\n return this.req.body;\n }\n}\n","export class JsonResource {\n public resource: any;\n\n constructor(resource: any) {\n this.resource = resource;\n }\n\n static make(resource: any): JsonResource {\n return new this(resource);\n }\n\n static collection(resource: any[]): AnonymousResourceCollection {\n return new AnonymousResourceCollection(resource, this);\n }\n\n resolve(request?: any): any {\n if (this.resource === null) {\n return null;\n }\n\n if (Array.isArray(this.resource)) {\n return this.resource.map((item) => {\n const instance = new (this.constructor as any)(item);\n return instance.toArray(request);\n });\n }\n\n return this.toArray(request);\n }\n\n toArray(request?: any): any {\n if (this.resource && typeof this.resource.toJSON === \"function\") {\n return this.resource.toJSON();\n }\n return this.resource;\n }\n}\n\nexport class AnonymousResourceCollection extends JsonResource {\n public collects: any;\n\n constructor(resource: any[], collects: any) {\n super(resource);\n this.collects = collects;\n }\n\n resolve(request?: any): any {\n return this.resource.map((item: any) => {\n const instance = new this.collects(item);\n return instance.resolve(request);\n });\n }\n}\n"],"names":["installedChunks","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","exports","module","__webpack_modules__","m","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","f","e","chunkId","Promise","all","keys","reduce","promises","u","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","require","installedChunk","chunk","moreModules","modules","chunkIds","ids","runtime","i","length","installChunk","Macroable","macro","name","this","macros","mixin","forEach","hasMacro","QueryBuilder","selectColumns","whereClauses","orderByClauses","joinClauses","constructor","table","adapter","super","tableName","select","columns","where","column","operator","push","boolean","orWhere","whereIn","values","whereNotIn","whereBetween","range","whereNull","whereNotNull","orderBy","direction","toUpperCase","limit","count","limitValue","offset","offsetValue","join","first","second","type","leftJoin","rightJoin","eagerLoads","setModel","model","with","relations","Array","isArray","options","joins","results","eagerLoadRelations","models","map","result","hydrate","relationName","instance","Error","relation","addEagerConstraints","relatedResults","match","find","id","pluck","row","sum","avg","min","max","exists","paginate","page","perPage","total","data","currentPage","lastPage","Math","ceil","clone","cloned","ValidationException","errors","status","Validator","registerValidator","fn","customValidators","rules","make","setDatabaseAdapter","databaseAdapter","fails","validateRules","passes","errors_","validate","validated","needsDatabaseAdapter","autoInjectDatabaseAdapter","field","ruleString","entries","split","getValue","rule","applyRule","ruleName","Container","container","getInstance","error","params","param","isEmpty","addError","isNaN","Number","isInteger","parseFloat","validateArrayContent","isValidJson","test","String","URL","validateMin","validateMax","includes","Date","parse","validateUnique","validateExists","validatorFn","array","item","itemField","JSON","parts","ignoreId","ignoreColumn","query","message","FormRequest","req","authorize","body","input","defaultValue","JsonResource","resource","collection","AnonymousResourceCollection","resolve","request","toArray","toJSON","collects"],"ignoreList":[],"sourceRoot":""}
|
package/dist/arcanox.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{"use strict";var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>"undefined"!=typeof require?require(id):eval("require")(id)},896:t=>{t.exports=require("fs")},928:t=>{t.exports=require("path")},941:t=>{t.exports=require("@faker-js/faker")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var i=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t](i,i.exports,__webpack_require__),i.exports}getProto=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,__webpack_require__.t=function(t,e){if(1&e&&(t=this(t)),8&e)return t;if("object"==typeof t&&t){if(4&e&&t.__esModule)return t;if(16&e&&"function"==typeof t.then)return t}var i=Object.create(null);__webpack_require__.r(i);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&e&&t;("object"==typeof s||"function"==typeof s)&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach(e=>r[e]=()=>t[e]);return r.default=()=>t,__webpack_require__.d(i,r),i},__webpack_require__.d=(t,e)=>{for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Blueprint:()=>Blueprint,Factory:()=>Factory,Macroable:()=>Macroable,Migration:()=>Migration,MigrationRunner:()=>MigrationRunner,Model:()=>Model,MongoAdapter:()=>MongoAdapter,MySQLAdapter:()=>MySQLAdapter,PostgresAdapter:()=>PostgresAdapter,QueryBuilder:()=>QueryBuilder,Schema:()=>Schema,Seeder:()=>Seeder});var dynamicRequire=__webpack_require__(14);class MongoAdapter{client=null;db=null;async connect(t){const{MongoClient:e}=(0,dynamicRequire.dynamicRequire)("mongodb"),i=`mongodb://${t.host}:${t.port}`;return this.client=new e(i,{auth:t.username&&t.password?{username:t.username,password:t.password}:void 0}),await this.client.connect(),this.db=this.client.db(t.database),{query:async(t,e)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(t,e)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(t,e){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(t)}async dropTable(t){if(!this.db)throw new Error("Database not connected");await this.db.collection(t).drop()}async hasTable(t){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:t}).toArray()).length>0}async hasColumn(t,e){return!0}async select(t,e){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(t),r=this.buildFilter(e.where||[]),s=this.buildProjection(e.columns);let n=i.find(r);if(s&&(n=n.project(s)),e.orderBy){const t={};e.orderBy.forEach(e=>{t[e.column]="ASC"===e.direction?1:-1}),n=n.sort(t)}return e.offset&&(n=n.skip(e.offset)),e.limit&&(n=n.limit(e.limit)),(await n.toArray()).map(t=>{const{_id:e,...i}=t;return{id:e,_id:e,...i}})}async insert(t,e){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(t),r={...e};r.id&&(r._id=r.id,delete r.id);const s=await i.insertOne(r);return{id:s.insertedId,_id:s.insertedId,...e}}async update(t,e,i){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(t),s={_id:this.normalizeId(e)},n={$set:i};await r.updateOne(s,n);const a=await r.findOne(s);if(a){const{_id:t,...e}=a;return{id:t,_id:t,...e}}return null}async delete(t,e){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(t);return 1===(await i.deleteOne({_id:this.normalizeId(e)})).deletedCount}async beginTransaction(){}async raw(t,e=[]){if(!this.db)throw new Error("Database not connected");return"db"===t?this.db:await this.db.command(JSON.parse(t))}async commit(){}async rollback(){}buildFilter(t){const e={};return t.forEach(t=>{const i="id"===t.column?"_id":t.column;let r=t.value;switch("_id"===i&&(r=this.normalizeId(r)),t.operator){case"=":e[i]=r;break;case"!=":e[i]={$ne:r};break;case">":e[i]={$gt:r};break;case"<":e[i]={$lt:r};break;case">=":e[i]={$gte:r};break;case"<=":e[i]={$lte:r};break;case"IN":e[i]={$in:Array.isArray(r)?r:[r]};break;case"NOT IN":e[i]={$nin:Array.isArray(r)?r:[r]};break;case"LIKE":e[i]={$regex:new RegExp(r.replace(/%/g,".*"),"i")};break;case"IS NULL":e[i]=null;break;case"IS NOT NULL":e[i]={$ne:null}}}),e}buildProjection(t){if(!t||0===t.length||t.includes("*"))return null;const e={};return t.forEach(t=>{"id"===t||(e[t]=1)}),e}normalizeId(t){const{ObjectId:e}=(0,dynamicRequire.dynamicRequire)("mongodb");return t instanceof e?t:"string"==typeof t&&e.isValid(t)?new e(t):t}}class MySQLAdapter{pool=null;connection=null;async connect(t){var e;const i=(0,dynamicRequire.dynamicRequire)("mysql2/promise");return this.pool=i.createPool({host:t.host,port:t.port,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:(null===(e=t.pool)||void 0===e?void 0:e.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(t,e){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.query(t,e);return i}async execute(t,e){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(t,e);return i}async createTable(t,e){const i=`CREATE TABLE IF NOT EXISTS \`${t}\` (${e.map(t=>{let e=`\`${t.name}\` ${this.mapType(t.type,t.length)}`;return t.unsigned&&(e+=" UNSIGNED"),t.autoIncrement&&(e+=" AUTO_INCREMENT"),t.nullable||(e+=" NOT NULL"),void 0!==t.default&&(e+=` DEFAULT ${this.formatValue(t.default)}`),t.primary&&(e+=" PRIMARY KEY"),t.unique&&(e+=" UNIQUE"),e}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(i)}async dropTable(t){await this.execute(`DROP TABLE IF EXISTS \`${t}\``)}async hasTable(t){var e;return(null===(e=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[t]))[0])||void 0===e?void 0:e.count)>0}async hasColumn(t,e){var i;return(null===(i=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[t,e]))[0])||void 0===i?void 0:i.count)>0}async select(t,e){var i;let r=`SELECT ${(null===(i=e.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM \`${t}\``;const s=[];if(e.joins&&e.joins.length>0)for(const t of e.joins)r+=` ${t.type} JOIN \`${t.table}\` ON ${t.first} ${t.operator} ${t.second}`;return e.where&&e.where.length>0&&(r+=" "+e.where.map((t,e)=>`${0===e?"WHERE":t.boolean} ${this.buildWhereCondition(t,s)}`).join(" ")),e.orderBy&&e.orderBy.length>0&&(r+=` ORDER BY ${e.orderBy.map(t=>`\`${t.column}\` ${t.direction}`).join(", ")}`),e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset)),await this.query(r,s)}async insert(t,e){const i=Object.keys(e),r=Object.values(e),s=r.map(()=>"?").join(", "),n=`INSERT INTO \`${t}\` (${i.map(t=>`\`${t}\``).join(", ")}) VALUES (${s})`;return{id:(await this.execute(n,r)).insertId,...e}}async update(t,e,i){const r=Object.keys(i),s=Object.values(i),n=`UPDATE \`${t}\` SET ${r.map(t=>`\`${t}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(n,[...s,e]),{id:e,...i}}async delete(t,e){const i=`DELETE FROM \`${t}\` WHERE id = ?`;return(await this.execute(i,[e])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(t,e=[]){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(t,e);return i}buildWhereCondition(t,e){const i=`\`${t.column}\``;switch(t.operator){case"IN":const r=t.value.map(()=>"?").join(", ");return e.push(...t.value),`${i} IN (${r})`;case"NOT IN":const s=t.value.map(()=>"?").join(", ");return e.push(...t.value),`${i} NOT IN (${s})`;case"BETWEEN":return e.push(t.value[0],t.value[1]),`${i} BETWEEN ? AND ?`;case"IS NULL":return`${i} IS NULL`;case"IS NOT NULL":return`${i} IS NOT NULL`;default:return e.push(t.value),`${i} ${t.operator} ?`}}mapType(t,e){return{string:e?`VARCHAR(${e})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[t]||t.toUpperCase()}formatValue(t){return null===t?"NULL":"string"==typeof t?`'${t.replace(/'/g,"''")}'`:"boolean"==typeof t?t?"1":"0":t instanceof Date?`'${t.toISOString().slice(0,19).replace("T"," ")}'`:String(t)}}class PostgresAdapter{pool=null;client=null;async connect(t){var e,i;const{Pool:r}=(0,dynamicRequire.dynamicRequire)("pg");return this.pool=new r({host:t.host,port:t.port,database:t.database,user:t.username,password:t.password,ssl:t.ssl,min:(null===(e=t.pool)||void 0===e?void 0:e.min)||2,max:(null===(i=t.pool)||void 0===i?void 0:i.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(t,e){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(t,e)).rows}async execute(t,e){if(!this.pool)throw new Error("Database not connected");return await this.pool.query(t,e)}async createTable(t,e){const i=`CREATE TABLE IF NOT EXISTS "${t}" (${e.map(t=>{let e=`"${t.name}" ${this.mapType(t.type,t.length)}`;return t.primary&&(e+=" PRIMARY KEY"),t.autoIncrement&&(e+=" GENERATED ALWAYS AS IDENTITY"),t.nullable||(e+=" NOT NULL"),t.unique&&(e+=" UNIQUE"),void 0!==t.default&&(e+=` DEFAULT ${this.formatValue(t.default)}`),e}).join(", ")})`;await this.execute(i)}async dropTable(t){await this.execute(`DROP TABLE IF EXISTS "${t}"`)}async hasTable(t){var e;return(null===(e=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[t]))[0])||void 0===e?void 0:e.exists)||!1}async hasColumn(t,e){var i;return(null===(i=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[t,e]))[0])||void 0===i?void 0:i.exists)||!1}async select(t,e){var i;let r=`SELECT ${(null===(i=e.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM "${t}"`;const s=[];let n=1;if(e.joins&&e.joins.length>0)for(const t of e.joins)r+=` ${t.type} JOIN "${t.table}" ON ${t.first} ${t.operator} ${t.second}`;return e.where&&e.where.length>0&&(r+=" "+e.where.map((t,e)=>{const i=0===e?"WHERE":t.boolean,r=this.buildWhereCondition(t,s,n);return n=s.length+1,`${i} ${r}`}).join(" ")),e.orderBy&&e.orderBy.length>0&&(r+=` ORDER BY ${e.orderBy.map(t=>`"${t.column}" ${t.direction}`).join(", ")}`),e.limit&&(r+=" LIMIT $"+n++,s.push(e.limit)),e.offset&&(r+=" OFFSET $"+n++,s.push(e.offset)),await this.query(r,s)}async insert(t,e){const i=Object.keys(e),r=Object.values(e),s=r.map((t,e)=>`$${e+1}`).join(", "),n=`INSERT INTO "${t}" (${i.map(t=>`"${t}"`).join(", ")}) \n VALUES (${s}) \n RETURNING *`;return(await this.query(n,r))[0]}async update(t,e,i){const r=Object.keys(i),s=Object.values(i),n=`UPDATE "${t}" SET ${r.map((t,e)=>`"${t}" = $${e+1}`).join(", ")} WHERE id = $${r.length+1} RETURNING *`;return(await this.query(n,[...s,e]))[0]}async delete(t,e){const i=`DELETE FROM "${t}" WHERE id = $1`;return(await this.execute(i,[e])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(t,e=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(t,e)).rows}buildWhereCondition(t,e,i){const r=`"${t.column}"`;switch(t.operator){case"IN":const s=t.value.map((t,e)=>`$${i+e}`).join(", ");return e.push(...t.value),`${r} IN (${s})`;case"NOT IN":const n=t.value.map((t,e)=>`$${i+e}`).join(", ");return e.push(...t.value),`${r} NOT IN (${n})`;case"BETWEEN":return e.push(t.value[0],t.value[1]),`${r} BETWEEN $${i} AND $${i+1}`;case"IS NULL":return`${r} IS NULL`;case"IS NOT NULL":return`${r} IS NOT NULL`;default:return e.push(t.value),`${r} ${t.operator} $${i}`}}mapType(t,e){return{string:e?`VARCHAR(${e})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[t]||t.toUpperCase()}formatValue(t){return null===t?"NULL":"string"==typeof t?`'${t.replace(/'/g,"''")}'`:"boolean"==typeof t?t?"TRUE":"FALSE":t instanceof Date?`'${t.toISOString()}'`:String(t)}}class Macroable{static macros={};static macro(t,e){this.macros[t]=e,this.prototype[t]=e}static mixin(t){Object.keys(t).forEach(e=>{this.macro(e,t[e])})}static hasMacro(t){return!!this.macros[t]}}class QueryBuilder extends Macroable{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(t,e){super(),this.tableName=t,this.adapter=e}select(...t){return this.selectColumns=t,this}where(t,e,i){return void 0===i&&(i=e,e="="),this.whereClauses.push({column:t,operator:e,value:i,boolean:"AND"}),this}orWhere(t,e,i){return void 0===i&&(i=e,e="="),this.whereClauses.push({column:t,operator:e,value:i,boolean:"OR"}),this}whereIn(t,e){return this.whereClauses.push({column:t,operator:"IN",value:e,boolean:"AND"}),this}whereNotIn(t,e){return this.whereClauses.push({column:t,operator:"NOT IN",value:e,boolean:"AND"}),this}whereBetween(t,e){return this.whereClauses.push({column:t,operator:"BETWEEN",value:e,boolean:"AND"}),this}whereNull(t){return this.whereClauses.push({column:t,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(t){return this.whereClauses.push({column:t,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(t,e="ASC"){return this.orderByClauses.push({column:t,direction:e.toUpperCase()}),this}limit(t){return this.limitValue=t,this}offset(t){return this.offsetValue=t,this}join(t,e,i,r,s="INNER"){return this.joinClauses.push({type:s,table:t,first:e,operator:i,second:r}),this}leftJoin(t,e,i,r){return this.join(t,e,i,r,"LEFT")}rightJoin(t,e,i,r){return this.join(t,e,i,r,"RIGHT")}eagerLoads=[];setModel(t){return this.model=t,this}with(t){return Array.isArray(t)?this.eagerLoads.push(...t):this.eagerLoads.push(t),this}async get(){const t={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},e=await this.adapter.select(this.tableName,t);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(e):e}async eagerLoadRelations(t){if(0===t.length)return t;const e=t.map(t=>this.model.hydrate(t));for(const t of this.eagerLoads){const i=new this.model;if("function"!=typeof i[t])throw new Error(`Relation ${t} does not exist on ${this.model.name}`);const r=i[t]();r.addEagerConstraints(e);const s=await r.get();r.match(e,s,t)}return e}async first(){return this.limit(1),(await this.get())[0]||null}async find(t){return this.where("id",t).first()}async count(){this.selectColumns=["COUNT(*) as count"];const t=await this.first();return t?t.count:0}async pluck(t){return this.select(t),(await this.get()).map(e=>e[t])}async sum(t){this.selectColumns=[`SUM(${t}) as sum`];const e=await this.first();return e&&e.sum||0}async avg(t){this.selectColumns=[`AVG(${t}) as avg`];const e=await this.first();return e&&e.avg||0}async min(t){this.selectColumns=[`MIN(${t}) as min`];const e=await this.first();return e?e.min:null}async max(t){this.selectColumns=[`MAX(${t}) as max`];const e=await this.first();return e?e.max:null}async exists(){return await this.count()>0}async paginate(t=1,e=15){const i=await this.count(),r=(t-1)*e;return this.limit(e).offset(r),{data:await this.get(),total:i,perPage:e,currentPage:t,lastPage:Math.ceil(i/e)}}clone(){const t=new QueryBuilder(this.tableName,this.adapter);return t.selectColumns=[...this.selectColumns],t.whereClauses=[...this.whereClauses],t.orderByClauses=[...this.orderByClauses],t.joinClauses=[...this.joinClauses],t.limitValue=this.limitValue,t.offsetValue=this.offsetValue,t}}class Relation{constructor(t,e){this.query=t,this.parent=e,this.related=t.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class BelongsTo extends Relation{constructor(t,e,i,r){super(t,e),this.foreignKey=i,this.ownerKey=r}addConstraints(){const t=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",t)}addEagerConstraints(t){const e=t.map(t=>t.getAttribute(this.foreignKey)).filter(t=>null!==t);this.query.whereIn(this.ownerKey,e)}match(t,e,i){const r={};return e.forEach(t=>{const e=t.getAttribute(this.ownerKey);r[e]=t}),t.forEach(t=>{const e=t.getAttribute(this.foreignKey);r[e]&&t.setRelation(i,r[e])}),t}}class BelongsToMany extends Relation{constructor(t,e,i,r,s,n,a){super(t,e),this.table=i,this.foreignPivotKey=r,this.relatedPivotKey=s,this.parentKey=n,this.relatedKey=a}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(t){const e=t||this.query,i=this.related.prototype.getTable();return e.join(this.table,`${i}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(t){this.performJoin();const e=t.map(t=>t.getAttribute(this.parentKey)).filter(t=>null!==t);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,e)}match(t,e,i){return t}}class HasMany extends Relation{constructor(t,e,i,r){super(t,e),this.foreignKey=i,this.localKey=r}addConstraints(){const t=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",t)}addEagerConstraints(t){const e=t.map(t=>t.getAttribute(this.localKey)).filter(t=>null!==t);this.query.whereIn(this.foreignKey,e)}match(t,e,i){const r={};return e.forEach(t=>{const e=t.getAttribute(this.foreignKey);r[e]||(r[e]=[]),r[e].push(t)}),t.forEach(t=>{const e=t.getAttribute(this.localKey);r[e]?t.setRelation(i,r[e]):t.setRelation(i,[])}),t}}class HasOne extends Relation{constructor(t,e,i,r){super(t,e),this.foreignKey=i,this.localKey=r}addConstraints(){const t=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",t)}addEagerConstraints(t){const e=t.map(t=>t.getAttribute(this.localKey)).filter(t=>null!==t);this.query.whereIn(this.foreignKey,e)}match(t,e,i){const r={};return e.forEach(t=>{const e=t.getAttribute(this.foreignKey);r[e]=t}),t.forEach(t=>{const e=t.getAttribute(this.localKey);r[e]&&t.setRelation(i,r[e])}),t}}class Model extends Macroable{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(t){this.adapter=t}static getTable(){if(this.tableName)return this.tableName;const t=this.name;return this.pluralize(this.snakeCase(t))}static query(){return new QueryBuilder(this.getTable(),this.adapter)}static async all(){return(await this.query().get()).map(t=>this.hydrate(t))}static async find(t){const e=await this.query().where(this.primaryKey,t).first();return e?this.hydrate(e):null}static async findOrFail(t){const e=await this.find(t);if(!e)throw new Error(`Model not found with ${this.primaryKey}: ${t}`);return e}static where(t,e,i){return this.query().where(t,e,i)}static async create(t){const e=new this;if(e.fill(t),e.timestamps){const t=new Date;e.attributes[e.createdAt]=t,e.attributes[e.updatedAt]=t}const i=await this.adapter.insert(this.getTable(),e.attributes),r=i[this.primaryKey]||i.id||i.insertId;return e.attributes[this.primaryKey]=r,"id"!==this.primaryKey&&(e.attributes.id=r),e.exists=!0,e.syncOriginal(),e}static async update(t,e){const i=await this.findOrFail(t);return await i.update(e),i}static async destroy(t){const e=await this.find(t);return!!e&&await e.delete()}static async firstOrCreate(t,e={}){const i=this.query();for(const[e,r]of Object.entries(t))i.where(e,r);const r=await i.first();return r?this.hydrate(r):await this.create({...t,...e})}static async updateOrCreate(t,e={}){const i=this.query();for(const[e,r]of Object.entries(t))i.where(e,r);const r=await i.first();if(r){const t=this.hydrate(r);return await t.update(e),t}return await this.create({...t,...e})}static hydrate(t){const e=new this;return e.attributes={...t},e.original={...t},e.exists=!0,e}fill(t){for(const[e,i]of Object.entries(t))this.isFillable(e)&&this.setAttribute(e,i);return this}isFillable(t){return this.fillable.length>0?this.fillable.includes(t):!this.guarded.includes(t)}setAttribute(t,e){const i=`set${this.studly(t)}Attribute`;"function"==typeof this[i]&&(e=this[i](e)),this.attributes[t]=this.castAttribute(t,e)}getAttribute(t){const e=`get${this.studly(t)}Attribute`;if("function"==typeof this[e])return this[e]();const i=this.attributes[t];return this.castAttribute(t,i,!0)}castAttribute(t,e,i=!1){if(null==e)return e;const r=this.casts[t];if(!r)return e;if(i)switch(r){case"int":case"integer":return parseInt(e);case"float":case"double":return parseFloat(e);case"string":return String(e);case"bool":case"boolean":return Boolean(e);case"array":case"json":return"string"==typeof e?JSON.parse(e):e;case"date":case"datetime":return e instanceof Date?e:new Date(e);default:return e}else switch(r){case"array":case"json":return"object"==typeof e?JSON.stringify(e):e;case"date":case"datetime":return e instanceof Date?e:new Date(e);default:return e}}async save(){const t=this.constructor;if(this.timestamps){const t=new Date;this.exists||(this.attributes[this.createdAt]=t),this.attributes[this.updatedAt]=t}if(this.exists){const e=this.attributes[t.primaryKey];await t.adapter.update(t.getTable(),e,this.attributes)}else{const e=await t.adapter.insert(t.getTable(),this.attributes),i=e[t.primaryKey]||e.id||e.insertId;this.attributes[t.primaryKey]=i,"id"!==t.primaryKey&&(this.attributes.id=i),this.exists=!0}return this.syncOriginal(),this}async update(t){return this.fill(t),await this.save()}async delete(){const t=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const e=this.attributes[t.primaryKey];return await t.adapter.delete(t.getTable(),e)}async forceDelete(){const t=this.constructor,e=this.attributes[t.primaryKey];return await t.adapter.delete(t.getTable(),e)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const t={};for(const[e,i]of Object.entries(this.attributes))this.original[e]!==i&&(t[e]=i);return t}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(t={}){super(),this.fill(t)}toJSON(){const t={};for(const[e,i]of Object.entries(this.attributes))this.hidden.includes(e)||this.visible.length>0&&!this.visible.includes(e)||(t[e]=this.getAttribute(e));for(const[e,i]of Object.entries(this.relations))t[e]=i;return t}hasOne(t,e,i){const r=new t,s=e||`${this.constructor.name.toLowerCase()}_id`,n=i||"id";return new HasOne(r.newQuery(),this,s,n)}hasMany(t,e,i){const r=new t,s=e||`${this.constructor.name.toLowerCase()}_id`,n=i||"id";return new HasMany(r.newQuery(),this,s,n)}belongsTo(t,e,i){const r=new t,s=e||`${r.constructor.name.toLowerCase()}_id`,n=i||"id";return new BelongsTo(r.newQuery(),this,s,n)}belongsToMany(t,e,i,r,s,n){const a=new t,o=e||this.guessPivotTable(a),c=i||`${this.constructor.name.toLowerCase()}_id`,l=r||`${a.constructor.name.toLowerCase()}_id`,u=s||"id",h=n||"id";return new BelongsToMany(a.newQuery(),this,o,c,l,u,h)}guessPivotTable(t){const e=[this.constructor.name.toLowerCase(),t.constructor.name.toLowerCase()];return e.sort(),e.join("_")}static with(t){return this.query().with(t)}setRelation(t,e){return this.relations[t]=e,this}getRelation(t){return this.relations[t]}relationLoaded(t){return void 0!==this.relations[t]}newQuery(){return this.constructor.query()}static snakeCase(t){return t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(t){return t.endsWith("y")?t.slice(0,-1)+"ies":t.endsWith("s")?t+"es":t+"s"}studly(t){return t.replace(/(^|_)(\w)/g,(t,e,i)=>i.toUpperCase())}}QueryBuilder.macro("populate",async function(t,e){const i=(await this.adapter.raw("db")).collection(this.tableName),r=(null==e?void 0:e.from)||`${t}s`,s=(null==e?void 0:e.localField)||`${t}_id`,n=(null==e?void 0:e.foreignField)||"_id",a=(null==e?void 0:e.as)||t,o=[];if(this.whereClauses&&this.whereClauses.length>0){var c,l;const t=(null===(c=(l=this.adapter).buildFilter)||void 0===c?void 0:c.call(l,this.whereClauses))||{};Object.keys(t).length>0&&o.push({$match:t})}if(null!=e&&e.select&&e.select.length>0){const t={};e.select.forEach(e=>{t[e]=1}),o.push({$lookup:{from:r,let:{localId:`$${s}`},pipeline:[{$match:{$expr:{$eq:[`$${n}`,"$$localId"]}}},{$project:t}],as:a}})}else o.push({$lookup:{from:r,localField:s,foreignField:n,as:a}});return o.push({$unwind:{path:`$${a}`,preserveNullAndEmptyArrays:!0}}),this.limitValue&&o.push({$limit:this.limitValue}),(await i.aggregate(o).toArray()).map(t=>{const{_id:e,...i}=t;return{id:e,_id:e,...i}})}),QueryBuilder.macro("exec",async function(){return await this.get()}),QueryBuilder.macro("aggregate",async function(t){const e=(await this.adapter.raw("db")).collection(this.tableName);return(await e.aggregate(t).toArray()).map(t=>{if(t._id){const{_id:e,...i}=t;return{id:e,_id:e,...i}}return t})});class ColumnBuilder{constructor(t,e,i){this.definition={name:t,type:e,length:i,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(t){return this.definition.default=t,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class ForeignKeyBuilder{constructor(t){this.column=t}references(t){return this.referencedColumn=t,this}on(t){return this.referencedTable=t,this}onDelete(t){return this.onDeleteAction=t,this}onUpdate(t){return this.onUpdateAction=t,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let t=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(t+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(t+=` ON UPDATE ${this.onUpdateAction}`),t}}class Blueprint{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(t){this.tableName=t}id(t="id"){const e=new ColumnBuilder(t,"bigInteger");return e.primary().autoIncrement().unsigned(),this.columns.push(e.getDefinition()),e}uuid(t="id"){const e=new ColumnBuilder(t,"uuid");return this.columns.push(e.getDefinition()),e}string(t,e=255){const i=new ColumnBuilder(t,"string",e);return this.columns.push(i.getDefinition()),i}text(t){const e=new ColumnBuilder(t,"text");return this.columns.push(e.getDefinition()),e}integer(t){const e=new ColumnBuilder(t,"integer");return this.columns.push(e.getDefinition()),e}bigInteger(t){const e=new ColumnBuilder(t,"bigInteger");return this.columns.push(e.getDefinition()),e}decimal(t,e=10,i=2){const r=new ColumnBuilder(t,"decimal");return this.columns.push(r.getDefinition()),r}float(t){const e=new ColumnBuilder(t,"float");return this.columns.push(e.getDefinition()),e}double(t){const e=new ColumnBuilder(t,"double");return this.columns.push(e.getDefinition()),e}boolean(t){const e=new ColumnBuilder(t,"boolean");return this.columns.push(e.getDefinition()),e}date(t){const e=new ColumnBuilder(t,"date");return this.columns.push(e.getDefinition()),e}datetime(t){const e=new ColumnBuilder(t,"datetime");return this.columns.push(e.getDefinition()),e}timestamp(t){const e=new ColumnBuilder(t,"timestamp");return this.columns.push(e.getDefinition()),e}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(t="deleted_at"){return this.timestamp(t).nullable()}json(t){const e=new ColumnBuilder(t,"json");return this.columns.push(e.getDefinition()),e}enum(t,e){const i=new ColumnBuilder(t,"enum");return this.columns.push(i.getDefinition()),i}foreign(t){const e=new ForeignKeyBuilder(t);return this.foreignKeys.push(e),e}index(t,e){const i=Array.isArray(t)?t:[t];this.indexes.push({columns:i,unique:!1,name:e})}unique(t,e){const i=Array.isArray(t)?t:[t];this.indexes.push({columns:i,unique:!0,name:e})}primary(t){this.primaryKeys=Array.isArray(t)?t:[t]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}class Schema{static setAdapter(t){this.adapter=t}static async create(t,e){const i=new Blueprint(t);e(i),await this.adapter.createTable(t,i.getColumns())}static async table(t,e){e(new Blueprint(t)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(t){await this.adapter.dropTable(t)}static async dropIfExists(t){await this.hasTable(t)&&await this.drop(t)}static async rename(t,e){throw new Error("Schema.rename() not yet implemented")}static async hasTable(t){return await this.adapter.hasTable(t)}static async hasColumn(t,e){return await this.adapter.hasColumn(t,e)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(t){throw new Error("Schema.getColumns() not yet implemented")}}class Migration{}class MigrationRunner{migrationsTable="migrations";constructor(t,e){this.adapter=t,this.migrationsPath=e}async ensureMigrationsTable(){await Schema.hasTable(this.migrationsTable)||await Schema.create(this.migrationsTable,t=>{t.id(),t.string("migration"),t.integer("batch"),t.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const t=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),e=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(t=>t.migration));return t.readdirSync(this.migrationsPath).filter(t=>t.endsWith(".ts")||t.endsWith(".js")).filter(t=>!e.includes(t.replace(/\.(ts|js)$/,""))).sort()}async run(){const t=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),e=await this.getPendingMigrations();if(0===e.length)return void console.log("No pending migrations");const i=await this.getRanMigrations(),r=i.length>0?Math.max(...i.map(t=>t.batch))+1:1;console.log(`Running ${e.length} migration(s)...`);for(const i of e){const e=t.resolve(this.migrationsPath,i),s=i.replace(/\.(ts|js)$/,"");try{const t=new(await this.loadMigration(e));console.log(`Migrating: ${s}`),await t.up(),await this.adapter.insert(this.migrationsTable,{migration:s,batch:r,created_at:new Date}),console.log(`Migrated: ${s}`)}catch(t){throw console.error(`Failed to migrate ${s}:`,t),t}}console.log("Migrations completed successfully")}async rollback(t=1){const e=await this.getRanMigrations();if(0===e.length)return void console.log("No migrations to rollback");const i=Math.max(...e.map(t=>t.batch)),r=i-t+1,s=e.filter(t=>t.batch>=r&&t.batch<=i).reverse();console.log(`Rolling back ${s.length} migration(s)...`);const n=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const t of s){const e=n.resolve(this.migrationsPath,`${t.migration}.ts`);try{const i=new(await this.loadMigration(e));console.log(`Rolling back: ${t.migration}`),await i.down(),await this.adapter.delete(this.migrationsTable,t.id),console.log(`Rolled back: ${t.migration}`)}catch(e){throw console.error(`Failed to rollback ${t.migration}:`,e),e}}console.log("Rollback completed successfully")}async reset(){const t=await this.getRanMigrations(),e=Math.max(...t.map(t=>t.batch));await this.rollback(e)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(t=>({name:t.migration,batch:t.batch,ranAt:t.created_at||new Date}))}async loadMigration(t){const e=(0,dynamicRequire.dynamicRequire)(t),i=e.default||e;if(!i||"function"!=typeof i)throw new Error(`Migration file ${t} does not export a valid migration class`);const r=new i;if("function"!=typeof r.up||"function"!=typeof r.down)throw new Error(`Migration class in ${t} must implement up() and down() methods`);return i}}class Factory{constructor(){this.faker=__webpack_require__(941).faker}make(t={}){const e=new this.model,i={...this.definition(),...t};return e.fill(i),e}async create(t={}){const e=this.make(t);return await e.save(),e}async createMany(t,e={}){const i=[];for(let r=0;r<t;r++)i.push(await this.create(e));return i}}class Seeder{async call(t){const e=new t;await e.run()}}var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>{try{var _global$process;const e=global,t=null===(_global$process=e.process)||void 0===_global$process||null===(_global$process=_global$process.mainModule)||void 0===_global$process?void 0:_global$process.require;if(t)return t(id)}catch(e){}return eval("require")(id)}},590:(e,t,i)=>{i.d(t,{PostgresAdapter:()=>s});var r=i(14);class s{pool=null;client=null;async connect(e){var t,i;const{Pool:s}=(0,r.dynamicRequire)("pg");return this.pool=new s({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,ssl:e.ssl,min:(null===(t=e.pool)||void 0===t?void 0:t.min)||2,max:(null===(i=e.pool)||void 0===i?void 0:i.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}async execute(e,t){if(!this.pool)throw new Error("Database not connected");return await this.pool.query(e,t)}async createTable(e,t){const i=`CREATE TABLE IF NOT EXISTS "${e}" (${t.map(e=>{let t=`"${e.name}" ${this.mapType(e.type,e.length)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" GENERATED ALWAYS AS IDENTITY"),e.nullable||(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),t}).join(", ")})`;await this.execute(i)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS "${e}"`)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[e]))[0])||void 0===t?void 0:t.exists)||!1}async hasColumn(e,t){var i;return(null===(i=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[e,t]))[0])||void 0===i?void 0:i.exists)||!1}async select(e,t){var i;let r=`SELECT ${(null===(i=t.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM "${e}"`;const s=[];let a=1;if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN "${e.table}" ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>{const i=0===t?"WHERE":e.boolean,r=this.buildWhereCondition(e,s,a);return a=s.length+1,`${i} ${r}`}).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`"${e.column}" ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT $"+a++,s.push(t.limit)),t.offset&&(r+=" OFFSET $"+a++,s.push(t.offset)),await this.query(r,s)}async insert(e,t){const i=Object.keys(t),r=Object.values(t),s=r.map((e,t)=>`$${t+1}`).join(", "),a=`INSERT INTO "${e}" (${i.map(e=>`"${e}"`).join(", ")}) \n VALUES (${s}) \n RETURNING *`;return(await this.query(a,r))[0]}async update(e,t,i){const r=Object.keys(i),s=Object.values(i),a=`UPDATE "${e}" SET ${r.map((e,t)=>`"${e}" = $${t+1}`).join(", ")} WHERE id = $${r.length+1} RETURNING *`;return(await this.query(a,[...s,t]))[0]}async delete(e,t){const i=`DELETE FROM "${e}" WHERE id = $1`;return(await this.execute(i,[t])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}buildWhereCondition(e,t,i){const r=`"${e.column}"`;switch(e.operator){case"IN":const s=e.value.map((e,t)=>`$${i+t}`).join(", ");return t.push(...e.value),`${r} IN (${s})`;case"NOT IN":const a=e.value.map((e,t)=>`$${i+t}`).join(", ");return t.push(...e.value),`${r} NOT IN (${a})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${r} BETWEEN $${i} AND $${i+1}`;case"IS NULL":return`${r} IS NULL`;case"IS NOT NULL":return`${r} IS NOT NULL`;default:return t.push(e.value),`${r} ${e.operator} $${i}`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:String(e)}}},697:(e,t,i)=>{i.d(t,{MongoAdapter:()=>s});var r=i(14);class s{client=null;db=null;async connect(e){const{MongoClient:t}=(0,r.dynamicRequire)("mongodb"),i=`mongodb://${e.host}:${e.port}`;return this.client=new t(i,{auth:e.username&&e.password?{username:e.username,password:e.password}:void 0}),await this.client.connect(),this.db=this.client.db(e.database),{query:async(e,t)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(e,t)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(e,t){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(e)}async dropTable(e){if(!this.db)throw new Error("Database not connected");await this.db.collection(e).drop()}async hasTable(e){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:e}).toArray()).length>0}async hasColumn(e,t){return!0}async select(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e),r=this.buildFilter(t.where||[]),s=this.buildProjection(t.columns);let a=i.find(r);if(s&&(a=a.project(s)),t.orderBy){const e={};t.orderBy.forEach(t=>{e[t.column]="ASC"===t.direction?1:-1}),a=a.sort(e)}return t.offset&&(a=a.skip(t.offset)),t.limit&&(a=a.limit(t.limit)),(await a.toArray()).map(e=>{const{_id:t,...i}=e;return{id:t,_id:t,...i}})}async insert(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e),r={...t};r.id&&(r._id=r.id,delete r.id);const s=await i.insertOne(r);return{id:s.insertedId,_id:s.insertedId,...t}}async update(e,t,i){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e),s={_id:this.normalizeId(t)},a={$set:i};await r.updateOne(s,a);const n=await r.findOne(s);if(n){const{_id:e,...t}=n;return{id:e,_id:e,...t}}return null}async delete(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e);return 1===(await i.deleteOne({_id:this.normalizeId(t)})).deletedCount}async beginTransaction(){}async raw(e,t=[]){if(!this.db)throw new Error("Database not connected");return"db"===e?this.db:await this.db.command(JSON.parse(e))}async commit(){}async rollback(){}buildFilter(e){const t={};return e.forEach(e=>{const i="id"===e.column?"_id":e.column;let r=e.value;switch("_id"===i&&(r=this.normalizeId(r)),e.operator){case"=":t[i]=r;break;case"!=":t[i]={$ne:r};break;case">":t[i]={$gt:r};break;case"<":t[i]={$lt:r};break;case">=":t[i]={$gte:r};break;case"<=":t[i]={$lte:r};break;case"IN":t[i]={$in:Array.isArray(r)?r:[r]};break;case"NOT IN":t[i]={$nin:Array.isArray(r)?r:[r]};break;case"LIKE":t[i]={$regex:new RegExp(r.replace(/%/g,".*"),"i")};break;case"IS NULL":t[i]=null;break;case"IS NOT NULL":t[i]={$ne:null}}}),t}buildProjection(e){if(!e||0===e.length||e.includes("*"))return null;const t={};return e.forEach(e=>{"id"===e||(t[e]=1)}),t}normalizeId(e){const{ObjectId:t}=(0,r.dynamicRequire)("mongodb");return e instanceof t?e:"string"==typeof e&&t.isValid(e)?new t(e):e}}},707:(e,t,i)=>{i.d(t,{MySQLAdapter:()=>s});var r=i(14);class s{pool=null;connection=null;async connect(e){var t;const i=(0,r.dynamicRequire)("mysql2/promise");return this.pool=i.createPool({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,waitForConnections:!0,connectionLimit:(null===(t=e.pool)||void 0===t?void 0:t.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.query(e,t);return i}async execute(e,t){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(e,t);return i}async createTable(e,t){const i=`CREATE TABLE IF NOT EXISTS \`${e}\` (${t.map(e=>{let t=`\`${e.name}\` ${this.mapType(e.type,e.length)}`;return e.unsigned&&(t+=" UNSIGNED"),e.autoIncrement&&(t+=" AUTO_INCREMENT"),e.nullable||(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),e.primary&&(t+=" PRIMARY KEY"),e.unique&&(t+=" UNIQUE"),t}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(i)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS \`${e}\``)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[e]))[0])||void 0===t?void 0:t.count)>0}async hasColumn(e,t){var i;return(null===(i=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[e,t]))[0])||void 0===i?void 0:i.count)>0}async select(e,t){var i;let r=`SELECT ${(null===(i=t.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM \`${e}\``;const s=[];if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN \`${e.table}\` ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>`${0===t?"WHERE":e.boolean} ${this.buildWhereCondition(e,s)}`).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`\`${e.column}\` ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT ?",s.push(t.limit)),t.offset&&(r+=" OFFSET ?",s.push(t.offset)),await this.query(r,s)}async insert(e,t){const i=Object.keys(t),r=Object.values(t),s=r.map(()=>"?").join(", "),a=`INSERT INTO \`${e}\` (${i.map(e=>`\`${e}\``).join(", ")}) VALUES (${s})`;return{id:(await this.execute(a,r)).insertId,...t}}async update(e,t,i){const r=Object.keys(i),s=Object.values(i),a=`UPDATE \`${e}\` SET ${r.map(e=>`\`${e}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(a,[...s,t]),{id:t,...i}}async delete(e,t){const i=`DELETE FROM \`${e}\` WHERE id = ?`;return(await this.execute(i,[t])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(e,t);return i}buildWhereCondition(e,t){const i=`\`${e.column}\``;switch(e.operator){case"IN":const r=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${i} IN (${r})`;case"NOT IN":const s=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${i} NOT IN (${s})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${i} BETWEEN ? AND ?`;case"IS NULL":return`${i} IS NULL`;case"IS NOT NULL":return`${i} IS NOT NULL`;default:return t.push(e.value),`${i} ${e.operator} ?`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString().slice(0,19).replace("T"," ")}'`:String(e)}}},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")},941:e=>{e.exports=require("@faker-js/faker")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](i,i.exports,__webpack_require__),i.exports}getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var i=Object.create(null);__webpack_require__.r(i);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;("object"==typeof s||"function"==typeof s)&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach(t=>r[t]=()=>e[t]);return r.default=()=>e,__webpack_require__.d(i,r),i},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BelongsTo:()=>BelongsTo,BelongsToMany:()=>BelongsToMany,Blueprint:()=>Blueprint,DatabaseProvider:()=>DatabaseProvider,Factory:()=>Factory,HasMany:()=>HasMany,HasOne:()=>HasOne,Macroable:()=>Macroable,Migration:()=>Migration,MigrationRunner:()=>MigrationRunner,Model:()=>Model,MongoAdapter:()=>MongoAdapter.MongoAdapter,MySQLAdapter:()=>MySQLAdapter.MySQLAdapter,PostgresAdapter:()=>PostgresAdapter.PostgresAdapter,QueryBuilder:()=>QueryBuilder,Relation:()=>Relation,Schema:()=>Schema,Seeder:()=>Seeder});var MongoAdapter=__webpack_require__(697),MySQLAdapter=__webpack_require__(707),PostgresAdapter=__webpack_require__(590);class Macroable{static macros={};static macro(e,t){this.macros[e]=t,this.prototype[e]=t}static mixin(e){Object.keys(e).forEach(t=>{this.macro(t,e[t])})}static hasMacro(e){return!!this.macros[e]}}class QueryBuilder extends Macroable{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(e,t){super(),this.tableName=e,this.adapter=t}select(...e){return this.selectColumns=e,this}where(e,t,i){return void 0===i&&(i=t,t="="),this.whereClauses.push({column:e,operator:t,value:i,boolean:"AND"}),this}orWhere(e,t,i){return void 0===i&&(i=t,t="="),this.whereClauses.push({column:e,operator:t,value:i,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({column:e,operator:"IN",value:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({column:e,operator:"NOT IN",value:t,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({column:e,operator:"BETWEEN",value:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({column:e,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({column:e,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(e,t="ASC"){return this.orderByClauses.push({column:e,direction:t.toUpperCase()}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}join(e,t,i,r,s="INNER"){return this.joinClauses.push({type:s,table:e,first:t,operator:i,second:r}),this}leftJoin(e,t,i,r){return this.join(e,t,i,r,"LEFT")}rightJoin(e,t,i,r){return this.join(e,t,i,r,"RIGHT")}eagerLoads=[];setModel(e){return this.model=e,this}with(e){return Array.isArray(e)?this.eagerLoads.push(...e):this.eagerLoads.push(e),this}async get(){const e={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},t=await this.adapter.select(this.tableName,e);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(t):t}async eagerLoadRelations(e){if(0===e.length)return e;const t=e.map(e=>this.model.hydrate(e));for(const e of this.eagerLoads){const i=new this.model;if("function"!=typeof i[e])throw new Error(`Relation ${e} does not exist on ${this.model.name}`);const r=i[e]();r.addEagerConstraints(t);const s=await r.get();r.match(t,s,e)}return t}async first(){return this.limit(1),(await this.get())[0]||null}async find(e){return this.where("id",e).first()}async count(){this.selectColumns=["COUNT(*) as count"];const e=await this.first();return e?e.count:0}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async sum(e){this.selectColumns=[`SUM(${e}) as sum`];const t=await this.first();return t&&t.sum||0}async avg(e){this.selectColumns=[`AVG(${e}) as avg`];const t=await this.first();return t&&t.avg||0}async min(e){this.selectColumns=[`MIN(${e}) as min`];const t=await this.first();return t?t.min:null}async max(e){this.selectColumns=[`MAX(${e}) as max`];const t=await this.first();return t?t.max:null}async exists(){return await this.count()>0}async paginate(e=1,t=15){const i=await this.count(),r=(e-1)*t;return this.limit(t).offset(r),{data:await this.get(),total:i,perPage:t,currentPage:e,lastPage:Math.ceil(i/t)}}clone(){const e=new QueryBuilder(this.tableName,this.adapter);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.orderByClauses=[...this.orderByClauses],e.joinClauses=[...this.joinClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e}}class Relation{constructor(e,t){this.query=e,this.parent=t,this.related=e.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class BelongsTo extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.ownerKey=r}addConstraints(){const e=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.foreignKey)).filter(e=>null!==e);this.query.whereIn(this.ownerKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.ownerKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]&&e.setRelation(i,r[t])}),e}}class BelongsToMany extends Relation{constructor(e,t,i,r,s,a,n){super(e,t),this.table=i,this.foreignPivotKey=r,this.relatedPivotKey=s,this.parentKey=a,this.relatedKey=n}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(e){const t=e||this.query,i=this.related.prototype.getTable();return t.join(this.table,`${i}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(e){this.performJoin();const t=e.map(e=>e.getAttribute(this.parentKey)).filter(e=>null!==e);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,t)}match(e,t,i){return e}}class HasMany extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]||(r[t]=[]),r[t].push(e)}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]?e.setRelation(i,r[t]):e.setRelation(i,[])}),e}}class HasOne extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]&&e.setRelation(i,r[t])}),e}}class Model extends Macroable{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(e){this.adapter=e}static getTable(){if(this.tableName)return this.tableName;const e=this.name;return this.pluralize(this.snakeCase(e))}static query(){return new QueryBuilder(this.getTable(),this.adapter)}static async all(){return(await this.query().get()).map(e=>this.hydrate(e))}static async find(e){const t=await this.query().where(this.primaryKey,e).first();return t?this.hydrate(t):null}static async findOrFail(e){const t=await this.find(e);if(!t)throw new Error(`Model not found with ${this.primaryKey}: ${e}`);return t}static where(e,t,i){return this.query().where(e,t,i)}static async create(e){const t=new this;if(t.fill(e),t.timestamps){const e=new Date;t.attributes[t.createdAt]=e,t.attributes[t.updatedAt]=e}const i=await this.adapter.insert(this.getTable(),t.attributes),r=i[this.primaryKey]||i.id||i.insertId;return t.attributes[this.primaryKey]=r,"id"!==this.primaryKey&&(t.attributes.id=r),t.exists=!0,t.syncOriginal(),t}static async update(e,t){const i=await this.findOrFail(e);return await i.update(t),i}static async destroy(e){const t=await this.find(e);return!!t&&await t.delete()}static async firstOrCreate(e,t={}){const i=this.query();for(const[t,r]of Object.entries(e))i.where(t,r);const r=await i.first();return r?this.hydrate(r):await this.create({...e,...t})}static async updateOrCreate(e,t={}){const i=this.query();for(const[t,r]of Object.entries(e))i.where(t,r);const r=await i.first();if(r){const e=this.hydrate(r);return await e.update(t),e}return await this.create({...e,...t})}static hydrate(e){const t=new this;return t.attributes={...e},t.original={...e},t.exists=!0,t}fill(e){for(const[t,i]of Object.entries(e))this.isFillable(t)&&this.setAttribute(t,i);return this}isFillable(e){return this.fillable.length>0?this.fillable.includes(e):!this.guarded.includes(e)}setAttribute(e,t){const i=`set${this.studly(e)}Attribute`;"function"==typeof this[i]&&(t=this[i](t)),this.attributes[e]=this.castAttribute(e,t)}getAttribute(e){const t=`get${this.studly(e)}Attribute`;if("function"==typeof this[t])return this[t]();const i=this.attributes[e];return this.castAttribute(e,i,!0)}castAttribute(e,t,i=!1){if(null==t)return t;const r=this.casts[e];if(!r)return t;if(i)switch(r){case"int":case"integer":return parseInt(t);case"float":case"double":return parseFloat(t);case"string":return String(t);case"bool":case"boolean":return Boolean(t);case"array":case"json":return"string"==typeof t?JSON.parse(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}else switch(r){case"array":case"json":return"object"==typeof t?JSON.stringify(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}}async save(){const e=this.constructor;if(this.timestamps){const e=new Date;this.exists||(this.attributes[this.createdAt]=e),this.attributes[this.updatedAt]=e}if(this.exists){const t=this.attributes[e.primaryKey];await e.adapter.update(e.getTable(),t,this.attributes)}else{const t=await e.adapter.insert(e.getTable(),this.attributes),i=t[e.primaryKey]||t.id||t.insertId;this.attributes[e.primaryKey]=i,"id"!==e.primaryKey&&(this.attributes.id=i),this.exists=!0}return this.syncOriginal(),this}async update(e){return this.fill(e),await this.save()}async delete(){const e=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async forceDelete(){const e=this.constructor,t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const e={};for(const[t,i]of Object.entries(this.attributes))this.original[t]!==i&&(e[t]=i);return e}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(e={}){super(),this.fill(e)}toJSON(){const e={};for(const[t,i]of Object.entries(this.attributes))this.hidden.includes(t)||this.visible.length>0&&!this.visible.includes(t)||(e[t]=this.getAttribute(t));for(const[t,i]of Object.entries(this.relations))e[t]=i;return e}hasOne(e,t,i){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,a=i||"id";return new HasOne(r.newQuery(),this,s,a)}hasMany(e,t,i){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,a=i||"id";return new HasMany(r.newQuery(),this,s,a)}belongsTo(e,t,i){const r=new e,s=t||`${r.constructor.name.toLowerCase()}_id`,a=i||"id";return new BelongsTo(r.newQuery(),this,s,a)}belongsToMany(e,t,i,r,s,a){const n=new e,o=t||this.guessPivotTable(n),c=i||`${this.constructor.name.toLowerCase()}_id`,l=r||`${n.constructor.name.toLowerCase()}_id`,u=s||"id",h=a||"id";return new BelongsToMany(n.newQuery(),this,o,c,l,u,h)}guessPivotTable(e){const t=[this.constructor.name.toLowerCase(),e.constructor.name.toLowerCase()];return t.sort(),t.join("_")}static with(e){return this.query().with(e)}setRelation(e,t){return this.relations[e]=t,this}getRelation(e){return this.relations[e]}relationLoaded(e){return void 0!==this.relations[e]}newQuery(){return this.constructor.query()}static snakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")?e+"es":e+"s"}studly(e){return e.replace(/(^|_)(\w)/g,(e,t,i)=>i.toUpperCase())}}class ColumnBuilder{constructor(e,t,i){this.definition={name:e,type:t,length:i,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(e){return this.definition.default=e,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class ForeignKeyBuilder{constructor(e){this.column=e}references(e){return this.referencedColumn=e,this}on(e){return this.referencedTable=e,this}onDelete(e){return this.onDeleteAction=e,this}onUpdate(e){return this.onUpdateAction=e,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let e=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(e+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(e+=` ON UPDATE ${this.onUpdateAction}`),e}}class Blueprint{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(e){this.tableName=e}id(e="id"){const t=new ColumnBuilder(e,"bigInteger");return t.primary().autoIncrement().unsigned(),this.columns.push(t.getDefinition()),t}uuid(e="id"){const t=new ColumnBuilder(e,"uuid");return this.columns.push(t.getDefinition()),t}string(e,t=255){const i=new ColumnBuilder(e,"string",t);return this.columns.push(i.getDefinition()),i}text(e){const t=new ColumnBuilder(e,"text");return this.columns.push(t.getDefinition()),t}integer(e){const t=new ColumnBuilder(e,"integer");return this.columns.push(t.getDefinition()),t}bigInteger(e){const t=new ColumnBuilder(e,"bigInteger");return this.columns.push(t.getDefinition()),t}decimal(e,t=10,i=2){const r=new ColumnBuilder(e,"decimal");return this.columns.push(r.getDefinition()),r}float(e){const t=new ColumnBuilder(e,"float");return this.columns.push(t.getDefinition()),t}double(e){const t=new ColumnBuilder(e,"double");return this.columns.push(t.getDefinition()),t}boolean(e){const t=new ColumnBuilder(e,"boolean");return this.columns.push(t.getDefinition()),t}date(e){const t=new ColumnBuilder(e,"date");return this.columns.push(t.getDefinition()),t}datetime(e){const t=new ColumnBuilder(e,"datetime");return this.columns.push(t.getDefinition()),t}timestamp(e){const t=new ColumnBuilder(e,"timestamp");return this.columns.push(t.getDefinition()),t}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(e="deleted_at"){return this.timestamp(e).nullable()}json(e){const t=new ColumnBuilder(e,"json");return this.columns.push(t.getDefinition()),t}enum(e,t){const i=new ColumnBuilder(e,"enum");return this.columns.push(i.getDefinition()),i}foreign(e){const t=new ForeignKeyBuilder(e);return this.foreignKeys.push(t),t}index(e,t){const i=Array.isArray(e)?e:[e];this.indexes.push({columns:i,unique:!1,name:t})}unique(e,t){const i=Array.isArray(e)?e:[e];this.indexes.push({columns:i,unique:!0,name:t})}primary(e){this.primaryKeys=Array.isArray(e)?e:[e]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}var dynamicRequire=__webpack_require__(14);class Schema{static setAdapter(e){this.adapter=e}static async create(e,t){const i=new Blueprint(e);t(i),await this.adapter.createTable(e,i.getColumns())}static async table(e,t){t(new Blueprint(e)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(e){await this.adapter.dropTable(e)}static async dropIfExists(e){await this.hasTable(e)&&await this.drop(e)}static async rename(e,t){throw new Error("Schema.rename() not yet implemented")}static async hasTable(e){return await this.adapter.hasTable(e)}static async hasColumn(e,t){return await this.adapter.hasColumn(e,t)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(e){throw new Error("Schema.getColumns() not yet implemented")}}class Migration{}class MigrationRunner{migrationsTable="migrations";constructor(e,t){this.adapter=e,this.migrationsPath=t}async ensureMigrationsTable(){await Schema.hasTable(this.migrationsTable)||await Schema.create(this.migrationsTable,e=>{e.id(),e.string("migration"),e.integer("batch"),e.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),t=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(e=>e.migration));return e.readdirSync(this.migrationsPath).filter(e=>e.endsWith(".ts")||e.endsWith(".js")).filter(e=>!t.includes(e.replace(/\.(ts|js)$/,""))).sort()}async run(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),t=await this.getPendingMigrations();if(0===t.length)return void console.log("No pending migrations");const i=await this.getRanMigrations(),r=i.length>0?Math.max(...i.map(e=>e.batch))+1:1;console.log(`Running ${t.length} migration(s)...`);for(const i of t){const t=e.resolve(this.migrationsPath,i),s=i.replace(/\.(ts|js)$/,"");try{const e=new(await this.loadMigration(t));console.log(`Migrating: ${s}`),await e.up(),await this.adapter.insert(this.migrationsTable,{migration:s,batch:r,created_at:new Date}),console.log(`Migrated: ${s}`)}catch(e){throw console.error(`Failed to migrate ${s}:`,e),e}}console.log("Migrations completed successfully")}async rollback(e=1){const t=await this.getRanMigrations();if(0===t.length)return void console.log("No migrations to rollback");const i=Math.max(...t.map(e=>e.batch)),r=i-e+1,s=t.filter(e=>e.batch>=r&&e.batch<=i).reverse();console.log(`Rolling back ${s.length} migration(s)...`);const a=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const e of s){const t=a.resolve(this.migrationsPath,`${e.migration}.ts`);try{const i=new(await this.loadMigration(t));console.log(`Rolling back: ${e.migration}`),await i.down(),await this.adapter.delete(this.migrationsTable,e.id),console.log(`Rolled back: ${e.migration}`)}catch(t){throw console.error(`Failed to rollback ${e.migration}:`,t),t}}console.log("Rollback completed successfully")}async reset(){const e=await this.getRanMigrations(),t=Math.max(...e.map(e=>e.batch));await this.rollback(t)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(e=>({name:e.migration,batch:e.batch,ranAt:e.created_at||new Date}))}async loadMigration(e){const t=(0,dynamicRequire.dynamicRequire)(e),i=t.default||t;if(!i||"function"!=typeof i)throw new Error(`Migration file ${e} does not export a valid migration class`);const r=new i;if("function"!=typeof r.up||"function"!=typeof r.down)throw new Error(`Migration class in ${e} must implement up() and down() methods`);return i}}class Factory{constructor(){this.faker=__webpack_require__(941).faker}make(e={}){const t=new this.model,i={...this.definition(),...e};return t.fill(i),t}async create(e={}){const t=this.make(e);return await t.save(),t}async createMany(e,t={}){const i=[];for(let r=0;r<e;r++)i.push(await this.create(t));return i}}class Seeder{async call(e){const t=new e;await t.run()}}QueryBuilder.macro("populate",async function(e,t){const i=(await this.adapter.raw("db")).collection(this.tableName),r=(null==t?void 0:t.from)||`${e}s`,s=(null==t?void 0:t.localField)||`${e}_id`,a=(null==t?void 0:t.foreignField)||"_id",n=(null==t?void 0:t.as)||e,o=[];if(this.whereClauses&&this.whereClauses.length>0){var c,l;const e=(null===(c=(l=this.adapter).buildFilter)||void 0===c?void 0:c.call(l,this.whereClauses))||{};Object.keys(e).length>0&&o.push({$match:e})}if(null!=t&&t.select&&t.select.length>0){const e={};t.select.forEach(t=>{e[t]=1}),o.push({$lookup:{from:r,let:{localId:`$${s}`},pipeline:[{$match:{$expr:{$eq:[`$${a}`,"$$localId"]}}},{$project:e}],as:n}})}else o.push({$lookup:{from:r,localField:s,foreignField:a,as:n}});return o.push({$unwind:{path:`$${n}`,preserveNullAndEmptyArrays:!0}}),this.limitValue&&o.push({$limit:this.limitValue}),(await i.aggregate(o).toArray()).map(e=>{const{_id:t,...i}=e;return{id:t,_id:t,...i}})}),QueryBuilder.macro("exec",async function(){return await this.get()}),QueryBuilder.macro("aggregate",async function(e){const t=(await this.adapter.raw("db")).collection(this.tableName);return(await t.aggregate(e).toArray()).map(e=>{if(e._id){const{_id:t,...i}=e;return{id:t,_id:t,...i}}return e})});class ServiceProvider{constructor(e){this.app=e}register(){}boot(){}async shutdown(){}}class DatabaseProvider extends ServiceProvider{async register(){let e;console.log("⚙️ DatabaseProvider: Initializing...");try{e=this.app.container.resolve("DatabaseConfig"),console.log("✓ DatabaseProvider: Configuration loaded successfully")}catch(e){return void console.warn("⚠ DatabaseProvider: No configuration found - Skipping setup")}try{let t;switch(console.log(`⚙️ DatabaseProvider: Loading ${e.type} adapter...`),e.type){case"mysql":const{MySQLAdapter:i}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,707));t=new i;break;case"mongodb":const{MongoAdapter:r}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,697));t=new r;break;case"postgres":const{PostgresAdapter:s}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,590));t=new s;break;default:throw new Error(`Unsupported database type: ${e.type}`)}console.log(`✓ DatabaseProvider: ${e.type} adapter loaded`),this.app.container.singleton("DatabaseAdapter",()=>t),this.app.container.singleton("DBConnection",async()=>{console.log(`⚙️ DatabaseProvider: Connecting to ${e.type}...`);const i=await t.connect(e);return Model.setAdapter(t),Schema.setAdapter(t),console.log(`✓ DatabaseProvider: Connected to ${e.type} database '${e.database}'`),i}),console.log("✅ DatabaseProvider: Ready")}catch(e){throw console.error("✗ DatabaseProvider: Initialization failed",e),e}}async shutdown(){try{console.log("⚙️ DatabaseProvider: Closing connection...");const e=await this.app.container.make("DatabaseAdapter");await e.disconnect(),console.log("✓ DatabaseProvider: Connection closed")}catch(e){}}}var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
|
|
2
2
|
//# sourceMappingURL=arcanox.js.map
|