arkormx 0.1.5 → 0.1.7
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/cli.mjs +17 -17
- package/dist/index.cjs +17 -17
- package/dist/index.d.cts +88 -3
- package/dist/index.d.mts +88 -3
- package/dist/index.mjs +10 -10
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdirSync as i,rmSync as a,writeFileSync as o}from"fs";import s,{dirname as c,extname as l,join as u,relative as d}from"path";import{createRequire as f}from"module";import{existsSync as p,mkdirSync as m,readFileSync as h,readdirSync as g,writeFileSync as _}from"node:fs";import{join as v,resolve as y}from"node:path";import{
|
|
3
|
-
`)}
|
|
4
|
-
`);t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${
|
|
5
|
-
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},se=(e,t)=>{let n=
|
|
2
|
+
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdirSync as i,rmSync as a,writeFileSync as o}from"fs";import s,{dirname as c,extname as l,join as u,relative as d}from"path";import{createRequire as f}from"module";import{existsSync as p,mkdirSync as m,readFileSync as h,readdirSync as g,writeFileSync as _}from"node:fs";import{join as v,resolve as y}from"node:path";import{spawnSync as ee}from"node:child_process";import{str as b}from"@h3ravel/support";import{fileURLToPath as te,pathToFileURL as ne}from"url";import{Logger as x}from"@h3ravel/shared";import{Command as S,Kernel as C}from"@h3ravel/musket";import{pathToFileURL as w}from"node:url";var T=class extends Error{constructor(e){super(e),this.name=`ArkormException`}},E=class{},D=class{columns=[];dropColumnNames=[];indexes=[];latestColumnName;primary(e,t){let n=typeof e==`string`?{columnName:e,...t??{}}:e??{},r=this.resolveColumn(n.columnName);return r.primary=!0,typeof n.autoIncrement==`boolean`&&(r.autoIncrement=n.autoIncrement),Object.prototype.hasOwnProperty.call(n,`default`)&&(r.default=n.default),this}id(e=`id`,t=`id`){return this.column(e,t,{primary:!0})}uuid(e,t={}){return this.column(e,`uuid`,t)}string(e,t={}){return this.column(e,`string`,t)}text(e,t={}){return this.column(e,`text`,t)}integer(e,t={}){return this.column(e,`integer`,t)}bigInteger(e,t={}){return this.column(e,`bigInteger`,t)}float(e,t={}){return this.column(e,`float`,t)}boolean(e,t={}){return this.column(e,`boolean`,t)}json(e,t={}){return this.column(e,`json`,t)}date(e,t={}){return this.column(e,`date`,t)}morphs(e,t=!1){return this.string(`${e}Type`,{nullable:t}),this.integer(`${e}Id`,{nullable:t}),this}nullableMorphs(e){return this.morphs(e,!0)}timestamp(e,t={}){return this.column(e,`timestamp`,t)}timestamps(){return this.timestamp(`createdAt`,{nullable:!1}),this.timestamp(`updatedAt`,{nullable:!1}),this}softDeletes(e=`deletedAt`){return this.timestamp(e,{nullable:!0}),this}dropColumn(e){return this.dropColumnNames.push(e),this}nullable(e){let t=this.resolveColumn(e);return t.nullable=!0,this}after(e,t){let n=this.resolveColumn(t);return n.after=e,this}map(e,t){let n=this.resolveColumn(t);return n.map=e,this}index(e,t){let n=Array.isArray(e)?e:typeof e==`string`?[e]:[this.resolveColumn().name];return this.indexes.push({columns:[...n],name:t}),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}getIndexes(){return this.indexes.map(e=>({...e,columns:[...e.columns]}))}column(e,t,n){return this.columns.push({name:e,type:t,map:n.map,nullable:n.nullable,unique:n.unique,primary:n.primary,autoIncrement:n.autoIncrement,after:n.after,default:n.default}),this.latestColumnName=e,this}resolveColumn(e){let t=e??this.latestColumnName;if(!t)throw Error(`No column available for this operation.`);let n=this.columns.find(e=>e.name===t);if(!n)throw Error(`Column [${t}] was not found in the table definition.`);return n}},re=class{operations=[];createTable(e,t){let n=new D;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns(),indexes:n.getIndexes()}),this}alterTable(e,t){let n=new D;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns(),addIndexes:n.getIndexes()}),this}dropTable(e){return this.operations.push({type:`dropTable`,table:e}),this}getOperations(){return this.operations.map(e=>e.type===`createTable`?{...e,columns:e.columns.map(e=>({...e})),indexes:e.indexes.map(e=>({...e,columns:[...e.columns]}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns],addIndexes:e.addIndexes.map(e=>({...e,columns:[...e.columns]}))}:{...e})}};const ie=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,O=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim(),n=(t.endsWith(`s`)&&t.length>1?t.slice(0,-1):t).split(/\s+/g).filter(Boolean);return n.length===0?`GeneratedModel`:n.map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)},k=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ae=e=>e.type===`id`?`Int`:e.type===`uuid`||e.type===`string`||e.type===`text`?`String`:e.type===`integer`?`Int`:e.type===`bigInteger`?`BigInt`:e.type===`float`?`Float`:e.type===`boolean`?`Boolean`:e.type===`json`?`Json`:`DateTime`,A=e=>{if(e!=null){if(typeof e==`string`)return`@default("${e.replace(/"/g,`\\"`)}")`;if(typeof e==`number`||typeof e==`bigint`)return`@default(${e})`;if(typeof e==`boolean`)return`@default(${e?`true`:`false`})`}},j=e=>{if(e.type===`id`){let t=e.primary===!1?``:` @id`,n=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,r=A(e.default),i=e.autoIncrement??e.primary!==!1,a=r?` ${r}`:i&&t?` @default(autoincrement())`:``;return` ${e.name} Int${t}${a}${n}`}let t=ae(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,o=A(e.default)??(e.type===`uuid`&&e.primary?`@default(uuid())`:void 0),s=o?` ${o}`:``;return` ${e.name} ${t}${n}${i}${r}${s}${a}`},M=e=>` @@index([${e.columns.join(`, `)}]${typeof e.name==`string`&&e.name.trim().length>0?`, name: "${e.name.replace(/"/g,`\\"`)}"`:``})`,N=e=>{let t=O(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(j),i=[...(e.indexes??[]).map(M),...n?[` @@map("${b(e.table).snake()}")`]:[]];return`model ${t} {\n${(i.length>0?[...r,``,...i]:r).join(`
|
|
3
|
+
`)}\n}`},P=(e,t)=>{let n=[...e.matchAll(ie)],r=RegExp(`@@map\\("${k(t)}"\\)`);for(let e of n){let n=e[0],i=e[1],a=e.index??0,o=a+n.length;if(r.test(n)||i.toLowerCase()===t.toLowerCase()||i.toLowerCase()===O(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},F=(e,t)=>{if(P(e,t.table))throw new T(`Prisma model for table [${t.table}] already exists.`);let n=N(t);return`${e.trimEnd()}\n\n${n}\n`},oe=(e,t)=>{let n=P(e,t.table);if(!n)throw new T(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
|
|
4
|
+
`);return t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${k(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}}),t.addColumns.forEach(e=>{let t=j(e),n=RegExp(`^\\s*${k(e.name)}\\s+`);if(i.some(e=>n.test(e)))return;let r=Math.max(1,i.length-1),a=typeof e.after==`string`&&e.after.length>0?i.findIndex(t=>RegExp(`^\\s*${k(e.after)}\\s+`).test(t)):-1,o=a>0?Math.min(a+1,r):r;i.splice(o,0,t)}),(t.addIndexes??[]).forEach(e=>{let t=M(e);if(i.some(e=>e.trim()===t.trim()))return;let n=Math.max(1,i.length-1);i.splice(n,0,t)}),r=i.join(`
|
|
5
|
+
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},se=(e,t)=>{let n=P(e,t.table);if(!n)return e;let r=e.slice(0,n.start).trimEnd(),i=e.slice(n.end).trimStart();return`${r}${r&&i?`
|
|
6
6
|
|
|
7
|
-
`:``}${i}`},
|
|
8
|
-
`).trim();throw new
|
|
7
|
+
`:``}${i}`},ce=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?F(e,t):t.type===`alterTable`?oe(e,t):se(e,t),e),I=(e,t)=>{let n=ee(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
|
|
8
|
+
`).trim();throw new T(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},L=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim();return t?`${t.split(/\s+/g).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)}Migration`:`GeneratedMigration`},R=e=>String(e).padStart(2,`0`),z=(e=new Date)=>`${e.getFullYear()}${R(e.getMonth()+1)}${R(e.getDate())}${R(e.getHours())}${R(e.getMinutes())}${R(e.getSeconds())}`,B=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,V=(e,t=`ts`)=>t===`js`?[`import { Migration } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async up (schema) {`,` }`,``,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async down (schema) {`,` }`,`}`,``].join(`
|
|
9
9
|
`):[`import { Migration, SchemaBuilder } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` public async up (schema: SchemaBuilder): Promise<void> {`,` }`,``,` public async down (schema: SchemaBuilder): Promise<void> {`,` }`,`}`,``].join(`
|
|
10
|
-
`),H=(e,t={})=>{let n=z(new Date),r=B(e),i=L(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=V(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new
|
|
10
|
+
`),H=(e,t={})=>{let n=z(new Date),r=B(e),i=L(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=V(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new T(`Migration file already exists: ${c}`);_(c,l)}return{fileName:s,filePath:c,className:i,content:l}},U=async(e,t=`up`)=>{let n=e instanceof E?e:new e,r=new re;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},W=async(e,t={})=>{let n=t.schemaPath??v(process.cwd(),`prisma`,`schema.prisma`);if(!p(n))throw new T(`Prisma schema file not found: ${n}`);let r=h(n,`utf-8`),i=await U(e,`up`),a=ce(r,i);return(t.write??!0)&&_(n,a),{schema:a,schemaPath:n,operations:i}},G=()=>{let e=s.dirname(te(import.meta.url));for(;;){let n=s.join(e,`package.json`),r=s.join(e,`stubs`);if(t(n)&&t(r))return r;let i=s.dirname(e);if(i===e)break;e=i}return s.join(process.cwd(),`stubs`)},K={paths:{stubs:G(),seeders:s.join(process.cwd(),`database`,`seeders`),models:s.join(process.cwd(),`src`,`models`),migrations:s.join(process.cwd(),`database`,`migrations`),factories:s.join(process.cwd(),`database`,`factories`),buildOutput:s.join(process.cwd(),`dist`)},outputExt:`ts`},q={...K,paths:{...K.paths??{}}};let J=!1,Y;const le=e=>{let t=K.paths??{},n=q.paths??{},r=Object.entries(e??{}).reduce((e,[t,n])=>(typeof n==`string`&&n.trim().length>0&&(e[t]=n),e),{});return{...t,...n,...r}},X=e=>e?q[e]:q,ue=(e,t={})=>{let n={...q,prisma:e,paths:le(t.paths)};t.pagination!==void 0&&(n.pagination=t.pagination),t.outputExt!==void 0&&(n.outputExt=t.outputExt),Object.assign(q,{...n}),n.pagination?.urlDriver},Z=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(ue(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),J=!0)},de=e=>import(`${ne(e).href}?arkorm_runtime=${Date.now()}`),fe=()=>{let e=f(import.meta.url),n=[s.join(process.cwd(),`arkormx.config.cjs`)];for(let r of n)if(t(r))try{return Z(e(r)),!0}catch{continue}return!1},pe=async()=>{if(!J){if(Y)return await Y;fe()||(Y=(async()=>{let e=[s.join(process.cwd(),`arkormx.config.js`),s.join(process.cwd(),`arkormx.config.ts`)];for(let n of e)if(t(n))try{Z(await de(n));return}catch{continue}J=!0})(),await Y)}},Q=()=>G();pe();var me=class{command;config={};constructor(){this.config=X()}getConfig=X;ensureDirectory(e){let r=c(e);t(r)||n(r,{recursive:!0})}formatPathForLog(e){let t=d(process.cwd(),e);return t?t.startsWith(`..`)?e:t:`.`}splitLogger(e,t){return t=t.includes(process.cwd())?this.formatPathForLog(t):t,x.twoColumnDetail(e+` `,` `+t,!1).join(``)}hasTypeScriptInstalled(){try{return f(import.meta.url).resolve(`typescript`,{paths:[process.cwd()]}),!0}catch{return!1}}resolveOutputExt(){let e=this.getConfig(`outputExt`)===`js`?`js`:`ts`;return e===`ts`&&!this.hasTypeScriptInstalled()?`js`:e}stripKnownSourceExtension(e){return e.replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}resolveRuntimeDirectoryPath(e){if(t(e))return e;let{buildOutput:n}=this.getConfig(`paths`)||{};if(typeof n!=`string`||n.trim().length===0)return e;let r=d(process.cwd(),e);if(!r||r.startsWith(`..`))return e;let i=u(n,r);return t(i)?i:e}resolveRuntimeScriptPath(e){let n=l(e).toLowerCase(),r=n===`.ts`||n===`.mts`||n===`.cts`,i=[];if(r){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}let{buildOutput:a}=this.getConfig(`paths`)??{};if(typeof a==`string`&&a.trim().length>0){let t=d(process.cwd(),e);if(t&&!t.startsWith(`..`)){let e=u(a,t),n=l(e).toLowerCase();if(n===`.ts`||n===`.mts`||n===`.cts`){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}else i.push(e)}}return i.find(e=>t(e))||e}generateFile(e,n,i,s){t(n)&&!s?.force?(this.command.error(`Error: ${this.formatPathForLog(n)} already exists.`),process.exit(1)):t(n)&&s?.force&&a(n);let c=r(e,`utf-8`);for(let[e,t]of Object.entries(i))c=c.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(n),o(n,c),n}resolveConfigPath(e,t){let{[e]:n}=this.getConfig(`paths`)??{};return typeof n==`string`&&n.trim().length>0?n:t}resolveStubPath(e){return u(this.resolveConfigPath(`stubs`,Q()),e)}makeFactory(e,t={}){let n=b(e.replace(/Factory$/,``)).pascal(),r=`${n}Factory`,i=t.modelName?b(t.modelName).pascal():n,a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${r}.${a}`),s=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${i}.${a}`),l=t.modelImportPath??`./${this.stripKnownSourceExtension(d(c(o),s).replace(/\\/g,`/`))}${a===`js`?`.js`:``}`,f=this.resolveStubPath(a===`js`?`factory.js.stub`:`factory.stub`);return{name:r,path:this.generateFile(f,o,{FactoryName:r,ModelName:i.toString(),ModelImportPath:l.startsWith(`.`)?l:`./${l}`},t)}}makeSeeder(e,t={}){let n=`${b(e.replace(/Seeder$/,``)).pascal()}Seeder`,r=this.resolveOutputExt(),i=u(this.resolveConfigPath(`seeders`,u(process.cwd(),`database`,`seeders`)),`${n}.${r}`),a=this.resolveStubPath(r===`js`?`seeder.js.stub`:`seeder.stub`);return{name:n,path:this.generateFile(a,i,{SeederName:n},t)}}makeMigration(e){let t=H(e,{directory:this.resolveConfigPath(`migrations`,u(process.cwd(),`database`,`migrations`)),extension:this.resolveOutputExt()});return{name:t.className,path:t.filePath}}makeModel(e,t={}){let n=b(e.replace(/Model$/,``)).pascal().toString(),r=`${n}`,i=b(n).camel().plural().toString(),a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${r}.${a}`),s=t.all||t.factory,l=t.all||t.seeder,f=t.all||t.migration,p=`${n}Factory`,m=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${p}.${a}`),h=`./${d(c(o),m).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`,g=this.resolveStubPath(a===`js`?`model.js.stub`:`model.stub`),_=this.generateFile(g,o,{ModelName:r,DelegateName:i,FactoryImport:s?`import { ${p} } from '${h}'\n`:``,FactoryLink:s?a===`js`?`\n static factoryClass = ${p}`:`\n protected static override factoryClass = ${p}`:``},t),v=this.ensurePrismaModelEntry(r,i),y={model:{name:r,path:_},prisma:v,factory:void 0,seeder:void 0,migration:void 0};return s&&(y.factory=this.makeFactory(n,{force:t.force,modelName:r,modelImportPath:`./${d(c(m),o).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`})),l&&(y.seeder=this.makeSeeder(n,{force:t.force})),f&&(y.migration=this.makeMigration(`create ${i} table`)),y}ensurePrismaModelEntry(e,n){let i=u(process.cwd(),`prisma`,`schema.prisma`);if(!t(i))return{path:i,updated:!1};let a=r(i,`utf-8`),s=P(a,n),c=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(a);return s||c?{path:i,updated:!1}:(o(i,F(a,{type:`createTable`,table:n,columns:[{name:`id`,type:`id`,primary:!0}]})),{path:i,updated:!0})}prismaTypeToTs(e){return e===`Int`||e===`Float`||e===`Decimal`?`number`:e===`BigInt`?`bigint`:e===`String`?`string`:e===`Boolean`?`boolean`:e===`DateTime`?`Date`:e===`Json`?`Record<string, unknown>`:e===`Bytes`?`Buffer`:`unknown`}parsePrismaModels(e){let t=[],n=/model\s+(\w+)\s*\{([\s\S]*?)\n\}/g,r=new Set([`Int`,`Float`,`Decimal`,`BigInt`,`String`,`Boolean`,`DateTime`,`Json`,`Bytes`]);for(let i of e.matchAll(n)){let e=i[1],n=i[2],a=n.match(/@@map\("([^"]+)"\)/)?.[1]??`${e.charAt(0).toLowerCase()}${e.slice(1)}s`,o=[];n.split(`
|
|
11
11
|
`).forEach(e=>{let t=e.trim();if(!t||t.startsWith(`@@`)||t.startsWith(`//`))return;let n=t.match(/^(\w+)\s+([A-Za-z]+)(\?)?\b/);if(!n)return;let i=n[2];r.has(i)&&o.push({name:n[1],type:this.prismaTypeToTs(i),optional:!!n[3]})}),t.push({name:e,table:a,fields:o})}return t}syncModelDeclarations(e,t){let n=e.split(`
|
|
12
12
|
`),r=n.findIndex(e=>/export\s+class\s+\w+\s+extends\s+Model<.+>\s*\{/.test(e));if(r<0)return{content:e,updated:!1};let i=-1,a=0;for(let e=r;e<n.length;e+=1){let t=n[e];if(a+=(t.match(/\{/g)||[]).length,a-=(t.match(/\}/g)||[]).length,a===0){i=e;break}}if(i<0)return{content:e,updated:!1};let o=n.slice(r+1,i).filter(e=>!/^\s*declare\s+\w+\??:\s*[^\n]+$/.test(e)),s=[...t.map(e=>` ${e}`),...o],c=[...n.slice(0,r+1),...s,...n.slice(i)].join(`
|
|
13
|
-
`);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let n=e.schemaPath??u(process.cwd(),`prisma`,`schema.prisma`),a=e.modelsDir??this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`));if(!t(n))throw Error(`Prisma schema file not found: ${n}`);if(!t(a))throw Error(`Models directory not found: ${a}`);let s=r(n,`utf-8`),c=this.parsePrismaModels(s),l=i(a).filter(e=>e.endsWith(`.ts`)),d=[],f=[];return l.forEach(e=>{let t=u(a,e),n=r(t,`utf-8`),i=n.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!i){f.push(t);return}let s=i[1],l=i[2],p=c.find(e=>e.table===l)??c.find(e=>e.name===s);if(!p||p.fields.length===0){f.push(t);return}let m=p.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),h=this.syncModelDeclarations(n,m);if(!h.updated){f.push(t);return}o(t,h.content),d.push(t)}),{schemaPath:n,modelsDir:a,total:l.length,updated:d,skipped:f}}},$=class extends
|
|
13
|
+
`);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let n=e.schemaPath??u(process.cwd(),`prisma`,`schema.prisma`),a=e.modelsDir??this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`));if(!t(n))throw Error(`Prisma schema file not found: ${n}`);if(!t(a))throw Error(`Models directory not found: ${a}`);let s=r(n,`utf-8`),c=this.parsePrismaModels(s),l=i(a).filter(e=>e.endsWith(`.ts`)),d=[],f=[];return l.forEach(e=>{let t=u(a,e),n=r(t,`utf-8`),i=n.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!i){f.push(t);return}let s=i[1],l=i[2],p=c.find(e=>e.table===l)??c.find(e=>e.name===s);if(!p||p.fields.length===0){f.push(t);return}let m=p.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),h=this.syncModelDeclarations(n,m);if(!h.updated){f.push(t);return}o(t,h.content),d.push(t)}),{schemaPath:n,modelsDir:a,total:l.length,updated:d,skipped:f}}},$=class extends S{signature=`init
|
|
14
14
|
{--force : Force overwrite if config file already exists (existing file will be backed up) }
|
|
15
|
-
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let n=v(process.cwd(),`arkormx.config.js`),{stubs:i}=X(`paths`)??{},a=typeof i==`string`&&i.trim().length>0?i:Q(),s=v(a,`arkormx.config.stub`),c=v(a,`arkorm.config.stub`),l=t(s)?s:c;t(n)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(n),t(n)&&this.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),t(l)||(this.error(`Error: Missing config stub at ${s} (or ${c})`),process.exit(1)),o(n,r(l,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},
|
|
15
|
+
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let n=v(process.cwd(),`arkormx.config.js`),{stubs:i}=X(`paths`)??{},a=typeof i==`string`&&i.trim().length>0?i:Q(),s=v(a,`arkormx.config.stub`),c=v(a,`arkorm.config.stub`),l=t(s)?s:c;t(n)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(n),t(n)&&this.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),t(l)||(this.error(`Error: Missing config stub at ${s} (or ${c})`),process.exit(1)),o(n,r(l,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},he=class extends S{signature=`make:factory
|
|
16
16
|
{name : Name of the factory to create}
|
|
17
17
|
{--f|force : Overwrite existing file}
|
|
18
|
-
`;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},
|
|
18
|
+
`;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},ge=class extends S{signature=`make:migration
|
|
19
19
|
{name : Name of the migration to create}
|
|
20
|
-
`;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},
|
|
20
|
+
`;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},_e=class extends S{signature=`make:model
|
|
21
21
|
{name : Name of the model to create}
|
|
22
22
|
{--f|force : Overwrite existing files}
|
|
23
23
|
{--factory : Create and link a factory}
|
|
24
24
|
{--seeder : Create a seeder}
|
|
25
25
|
{--migration : Create a migration}
|
|
26
26
|
{--all : Create and link factory, seeder, and migration}
|
|
27
|
-
`;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},
|
|
27
|
+
`;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},ve=class extends S{signature=`make:seeder
|
|
28
28
|
{name : Name of the seeder to create}
|
|
29
29
|
{--f|force : Overwrite existing file}
|
|
30
|
-
`;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},
|
|
30
|
+
`;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},ye=class extends S{signature=`migrate
|
|
31
31
|
{name? : Migration class or file name}
|
|
32
32
|
{--all : Run all migrations from the configured migrations directory}
|
|
33
33
|
{--deploy : Use prisma migrate deploy instead of migrate dev}
|
|
@@ -35,17 +35,17 @@ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdi
|
|
|
35
35
|
{--skip-migrate : Skip prisma migrate command}
|
|
36
36
|
{--schema= : Explicit prisma schema path}
|
|
37
37
|
{--migration-name= : Name for prisma migrate dev}
|
|
38
|
-
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??v(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?y(String(this.option(`schema`))):v(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await W(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||I([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?I([`migrate`,`deploy`],process.cwd()):I([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${
|
|
38
|
+
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??v(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?y(String(this.option(`schema`))):v(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await W(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||I([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?I([`migrate`,`deploy`],process.cwd()):I([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${w(y(e)).href}?arkorm_migrate=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof E:!1)}},be=class extends S{signature=`models:sync
|
|
39
39
|
{--schema= : Path to prisma schema file}
|
|
40
40
|
{--models= : Path to models directory}
|
|
41
|
-
`;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?y(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?y(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},
|
|
41
|
+
`;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?y(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?y(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},xe=class e{async call(...t){await e.runSeeders(...t)}static toSeederInstance(t){return t instanceof e?t:new t}static async runSeeders(...e){let t=e.reduce((e,t)=>Array.isArray(t)?[...e,...t]:(e.push(t),e),[]);for(let e of t)await this.toSeederInstance(e).run()}},Se=class extends S{signature=`seed
|
|
42
42
|
{name? : Seeder class or file name}
|
|
43
43
|
{--all : Run all seeders in the configured seeders directory}
|
|
44
|
-
`;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??v(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${
|
|
44
|
+
`;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??v(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${w(y(e)).href}?arkorm_seed=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof xe:!1)}},Ce=String.raw`
|
|
45
45
|
__/^^^^^^^^^^^^^^^^\__
|
|
46
46
|
▄▄▄/ \▄▄
|
|
47
47
|
▄██▀▀██▄ ▄▄
|
|
48
48
|
███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
|
|
49
49
|
███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
|
|
50
50
|
███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
|
|
51
|
-
`;const
|
|
51
|
+
`;const we=new me;await C.init(we,{logo:Ce,name:`Arkormˣ CLI`,baseCommands:[$,_e,he,ve,ge,be,Se,ye],exceptionHandler(e){throw e}});export{};
|
package/dist/index.cjs
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`),l=require(`path`);l=s(l);let u=require(`module`),d=require(`node:fs`),f=require(`node:path`),p=require(
|
|
2
|
-
`)}
|
|
3
|
-
`);t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${
|
|
4
|
-
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`),l=require(`path`);l=s(l);let u=require(`module`),d=require(`node:fs`),f=require(`node:path`),p=require(`node:child_process`),m=require(`@h3ravel/support`),h=require(`url`),ee=require(`@h3ravel/shared`),g=require(`@h3ravel/musket`),_=require(`node:url`),te=require(`@h3ravel/collect.js`);const ne={string:{get:e=>e==null?e:String(e),set:e=>e==null?e:String(e)},number:{get:e=>e==null?e:Number(e),set:e=>e==null?e:Number(e)},boolean:{get:e=>e==null?e:!!e,set:e=>e==null?e:!!e},date:{get:e=>e==null||e instanceof Date?e:new Date(String(e)),set:e=>e==null||e instanceof Date?e:new Date(String(e))},json:{get:e=>{if(e==null||typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},set:e=>e==null||typeof e==`string`?e:JSON.stringify(e)},array:{get:e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{return[e]}return e==null?e:[e]},set:e=>e==null||Array.isArray(e)?e:[e]}};function v(e){return typeof e==`string`?ne[e]:e}var y=class extends Error{constructor(e){super(e),this.name=`ArkormException`}},b=class{},x=class{columns=[];dropColumnNames=[];indexes=[];latestColumnName;primary(e,t){let n=typeof e==`string`?{columnName:e,...t??{}}:e??{},r=this.resolveColumn(n.columnName);return r.primary=!0,typeof n.autoIncrement==`boolean`&&(r.autoIncrement=n.autoIncrement),Object.prototype.hasOwnProperty.call(n,`default`)&&(r.default=n.default),this}id(e=`id`,t=`id`){return this.column(e,t,{primary:!0})}uuid(e,t={}){return this.column(e,`uuid`,t)}string(e,t={}){return this.column(e,`string`,t)}text(e,t={}){return this.column(e,`text`,t)}integer(e,t={}){return this.column(e,`integer`,t)}bigInteger(e,t={}){return this.column(e,`bigInteger`,t)}float(e,t={}){return this.column(e,`float`,t)}boolean(e,t={}){return this.column(e,`boolean`,t)}json(e,t={}){return this.column(e,`json`,t)}date(e,t={}){return this.column(e,`date`,t)}morphs(e,t=!1){return this.string(`${e}Type`,{nullable:t}),this.integer(`${e}Id`,{nullable:t}),this}nullableMorphs(e){return this.morphs(e,!0)}timestamp(e,t={}){return this.column(e,`timestamp`,t)}timestamps(){return this.timestamp(`createdAt`,{nullable:!1}),this.timestamp(`updatedAt`,{nullable:!1}),this}softDeletes(e=`deletedAt`){return this.timestamp(e,{nullable:!0}),this}dropColumn(e){return this.dropColumnNames.push(e),this}nullable(e){let t=this.resolveColumn(e);return t.nullable=!0,this}after(e,t){let n=this.resolveColumn(t);return n.after=e,this}map(e,t){let n=this.resolveColumn(t);return n.map=e,this}index(e,t){let n=Array.isArray(e)?e:typeof e==`string`?[e]:[this.resolveColumn().name];return this.indexes.push({columns:[...n],name:t}),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}getIndexes(){return this.indexes.map(e=>({...e,columns:[...e.columns]}))}column(e,t,n){return this.columns.push({name:e,type:t,map:n.map,nullable:n.nullable,unique:n.unique,primary:n.primary,autoIncrement:n.autoIncrement,after:n.after,default:n.default}),this.latestColumnName=e,this}resolveColumn(e){let t=e??this.latestColumnName;if(!t)throw Error(`No column available for this operation.`);let n=this.columns.find(e=>e.name===t);if(!n)throw Error(`Column [${t}] was not found in the table definition.`);return n}},re=class{operations=[];createTable(e,t){let n=new x;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns(),indexes:n.getIndexes()}),this}alterTable(e,t){let n=new x;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns(),addIndexes:n.getIndexes()}),this}dropTable(e){return this.operations.push({type:`dropTable`,table:e}),this}getOperations(){return this.operations.map(e=>e.type===`createTable`?{...e,columns:e.columns.map(e=>({...e})),indexes:e.indexes.map(e=>({...e,columns:[...e.columns]}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns],addIndexes:e.addIndexes.map(e=>({...e,columns:[...e.columns]}))}:{...e})}};const ie=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,S=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim(),n=(t.endsWith(`s`)&&t.length>1?t.slice(0,-1):t).split(/\s+/g).filter(Boolean);return n.length===0?`GeneratedModel`:n.map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)},C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ae=e=>e.type===`id`?`Int`:e.type===`uuid`||e.type===`string`||e.type===`text`?`String`:e.type===`integer`?`Int`:e.type===`bigInteger`?`BigInt`:e.type===`float`?`Float`:e.type===`boolean`?`Boolean`:e.type===`json`?`Json`:`DateTime`,w=e=>{if(e!=null){if(typeof e==`string`)return`@default("${e.replace(/"/g,`\\"`)}")`;if(typeof e==`number`||typeof e==`bigint`)return`@default(${e})`;if(typeof e==`boolean`)return`@default(${e?`true`:`false`})`}},T=e=>{if(e.type===`id`){let t=e.primary===!1?``:` @id`,n=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,r=w(e.default),i=e.autoIncrement??e.primary!==!1,a=r?` ${r}`:i&&t?` @default(autoincrement())`:``;return` ${e.name} Int${t}${a}${n}`}let t=ae(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,o=w(e.default)??(e.type===`uuid`&&e.primary?`@default(uuid())`:void 0),s=o?` ${o}`:``;return` ${e.name} ${t}${n}${i}${r}${s}${a}`},E=e=>` @@index([${e.columns.join(`, `)}]${typeof e.name==`string`&&e.name.trim().length>0?`, name: "${e.name.replace(/"/g,`\\"`)}"`:``})`,oe=e=>{let t=S(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(T),i=[...(e.indexes??[]).map(E),...n?[` @@map("${(0,m.str)(e.table).snake()}")`]:[]];return`model ${t} {\n${(i.length>0?[...r,``,...i]:r).join(`
|
|
2
|
+
`)}\n}`},D=(e,t)=>{let n=[...e.matchAll(ie)],r=RegExp(`@@map\\("${C(t)}"\\)`);for(let e of n){let n=e[0],i=e[1],a=e.index??0,o=a+n.length;if(r.test(n)||i.toLowerCase()===t.toLowerCase()||i.toLowerCase()===S(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},O=(e,t)=>{if(D(e,t.table))throw new y(`Prisma model for table [${t.table}] already exists.`);let n=oe(t);return`${e.trimEnd()}\n\n${n}\n`},k=(e,t)=>{let n=D(e,t.table);if(!n)throw new y(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
|
|
3
|
+
`);return t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${C(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}}),t.addColumns.forEach(e=>{let t=T(e),n=RegExp(`^\\s*${C(e.name)}\\s+`);if(i.some(e=>n.test(e)))return;let r=Math.max(1,i.length-1),a=typeof e.after==`string`&&e.after.length>0?i.findIndex(t=>RegExp(`^\\s*${C(e.after)}\\s+`).test(t)):-1,o=a>0?Math.min(a+1,r):r;i.splice(o,0,t)}),(t.addIndexes??[]).forEach(e=>{let t=E(e);if(i.some(e=>e.trim()===t.trim()))return;let n=Math.max(1,i.length-1);i.splice(n,0,t)}),r=i.join(`
|
|
4
|
+
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},A=(e,t)=>{let n=D(e,t.table);if(!n)return e;let r=e.slice(0,n.start).trimEnd(),i=e.slice(n.end).trimStart();return`${r}${r&&i?`
|
|
5
5
|
|
|
6
|
-
`:``}${i}`},
|
|
7
|
-
`).trim();throw new y(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},
|
|
6
|
+
`:``}${i}`},se=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?O(e,t):t.type===`alterTable`?k(e,t):A(e,t),e),j=(e,t)=>{let n=(0,p.spawnSync)(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
|
|
7
|
+
`).trim();throw new y(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},ce=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim();return t?`${t.split(/\s+/g).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)}Migration`:`GeneratedMigration`},M=e=>String(e).padStart(2,`0`),N=(e=new Date)=>`${e.getFullYear()}${M(e.getMonth()+1)}${M(e.getDate())}${M(e.getHours())}${M(e.getMinutes())}${M(e.getSeconds())}`,le=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,ue=(e,t=`ts`)=>t===`js`?[`import { Migration } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async up (schema) {`,` }`,``,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async down (schema) {`,` }`,`}`,``].join(`
|
|
8
8
|
`):[`import { Migration, SchemaBuilder } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` public async up (schema: SchemaBuilder): Promise<void> {`,` }`,``,` public async down (schema: SchemaBuilder): Promise<void> {`,` }`,`}`,``].join(`
|
|
9
|
-
`),de=(e,t={})=>{let n=
|
|
9
|
+
`),de=(e,t={})=>{let n=N(new Date),r=le(e),i=ce(e),a=t.extension??`ts`,o=t.directory??(0,f.join)(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=(0,f.join)(o,s),l=ue(i,a);if(t.write??!0){if((0,d.existsSync)(o)||(0,d.mkdirSync)(o,{recursive:!0}),(0,d.existsSync)(c))throw new y(`Migration file already exists: ${c}`);(0,d.writeFileSync)(c,l)}return{fileName:s,filePath:c,className:i,content:l}},fe=async(e,t=`up`)=>{let n=e instanceof b?e:new e,r=new re;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},P=async(e,t={})=>{let n=t.schemaPath??(0,f.join)(process.cwd(),`prisma`,`schema.prisma`);if(!(0,d.existsSync)(n))throw new y(`Prisma schema file not found: ${n}`);let r=(0,d.readFileSync)(n,`utf-8`),i=await fe(e,`up`),a=se(r,i);return(t.write??!0)&&(0,d.writeFileSync)(n,a),{schema:a,schemaPath:n,operations:i}},pe=async(e,t={})=>{let n=t.cwd??process.cwd(),r=await P(e,{schemaPath:t.schemaPath??(0,f.join)(n,`prisma`,`schema.prisma`),write:t.write}),i=t.runGenerate??!0,a=t.runMigrate??!0,o=t.migrateMode??`dev`;return i&&j([`generate`],n),a&&j(o===`deploy`?[`migrate`,`deploy`]:[`migrate`,`dev`,`--name`,t.migrationName??`arkorm_${N()}`],n),{schemaPath:r.schemaPath,operations:r.operations}},me=()=>{let e=l.default.dirname((0,h.fileURLToPath)(require(`url`).pathToFileURL(__filename).href));for(;;){let t=l.default.join(e,`package.json`),n=l.default.join(e,`stubs`);if((0,c.existsSync)(t)&&(0,c.existsSync)(n))return n;let r=l.default.dirname(e);if(r===e)break;e=r}return l.default.join(process.cwd(),`stubs`)},F={paths:{stubs:me(),seeders:l.default.join(process.cwd(),`database`,`seeders`),models:l.default.join(process.cwd(),`src`,`models`),migrations:l.default.join(process.cwd(),`database`,`migrations`),factories:l.default.join(process.cwd(),`database`,`factories`),buildOutput:l.default.join(process.cwd(),`dist`)},outputExt:`ts`},I={...F,paths:{...F.paths??{}}};let L=!1,R,z,B;const he=e=>{let t=F.paths??{},n=I.paths??{},r=Object.entries(e??{}).reduce((e,[t,n])=>(typeof n==`string`&&n.trim().length>0&&(e[t]=n),e),{});return{...t,...n,...r}},ge=e=>e,V=e=>e?I[e]:I,H=(e,t={})=>{let n={...I,prisma:e,paths:he(t.paths)};t.pagination!==void 0&&(n.pagination=t.pagination),t.outputExt!==void 0&&(n.outputExt=t.outputExt),Object.assign(I,{...n}),z=e,B=n.pagination?.urlDriver},_e=()=>{Object.assign(I,{...F,paths:{...F.paths??{}}}),L=!1,R=void 0,z=void 0,B=void 0},ve=e=>{if(!e)return;let t=typeof e==`function`?e():e;if(!(!t||typeof t!=`object`))return t},ye=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(H(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),L=!0)},be=e=>import(`${(0,h.pathToFileURL)(e).href}?arkorm_runtime=${Date.now()}`),U=()=>{let e=(0,u.createRequire)(e(`url`).pathToFileURL(__filename).href),t=[l.default.join(process.cwd(),`arkormx.config.cjs`)];for(let n of t)if((0,c.existsSync)(n))try{return ye(e(n)),!0}catch{continue}return!1},W=async()=>{if(!L){if(R)return await R;U()||(R=(async()=>{let e=[l.default.join(process.cwd(),`arkormx.config.js`),l.default.join(process.cwd(),`arkormx.config.ts`)];for(let t of e)if((0,c.existsSync)(t))try{ye(await be(t));return}catch{continue}L=!0})(),await R)}},xe=()=>{L||R||W()},G=()=>me(),Se=()=>(L||U(),ve(z)),K=()=>(L||U(),B),q=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return[`findMany`,`findFirst`,`create`,`update`,`delete`,`count`].every(e=>typeof t[e]==`function`)};W();var Ce=class{command;config={};constructor(){this.config=V()}getConfig=V;ensureDirectory(e){let t=(0,l.dirname)(e);(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0})}formatPathForLog(e){let t=(0,l.relative)(process.cwd(),e);return t?t.startsWith(`..`)?e:t:`.`}splitLogger(e,t){return t=t.includes(process.cwd())?this.formatPathForLog(t):t,ee.Logger.twoColumnDetail(e+` `,` `+t,!1).join(``)}hasTypeScriptInstalled(){try{return(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve(`typescript`,{paths:[process.cwd()]}),!0}catch{return!1}}resolveOutputExt(){let e=this.getConfig(`outputExt`)===`js`?`js`:`ts`;return e===`ts`&&!this.hasTypeScriptInstalled()?`js`:e}stripKnownSourceExtension(e){return e.replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}resolveRuntimeDirectoryPath(e){if((0,c.existsSync)(e))return e;let{buildOutput:t}=this.getConfig(`paths`)||{};if(typeof t!=`string`||t.trim().length===0)return e;let n=(0,l.relative)(process.cwd(),e);if(!n||n.startsWith(`..`))return e;let r=(0,l.join)(t,n);return(0,c.existsSync)(r)?r:e}resolveRuntimeScriptPath(e){let t=(0,l.extname)(e).toLowerCase(),n=t===`.ts`||t===`.mts`||t===`.cts`,r=[];if(n){let n=e.slice(0,-t.length);r.push(`${n}.js`,`${n}.cjs`,`${n}.mjs`)}let{buildOutput:i}=this.getConfig(`paths`)??{};if(typeof i==`string`&&i.trim().length>0){let t=(0,l.relative)(process.cwd(),e);if(t&&!t.startsWith(`..`)){let e=(0,l.join)(i,t),n=(0,l.extname)(e).toLowerCase();if(n===`.ts`||n===`.mts`||n===`.cts`){let t=e.slice(0,-n.length);r.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}else r.push(e)}}return r.find(e=>(0,c.existsSync)(e))||e}generateFile(e,t,n,r){(0,c.existsSync)(t)&&!r?.force?(this.command.error(`Error: ${this.formatPathForLog(t)} already exists.`),process.exit(1)):(0,c.existsSync)(t)&&r?.force&&(0,c.rmSync)(t);let i=(0,c.readFileSync)(e,`utf-8`);for(let[e,t]of Object.entries(n))i=i.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(t),(0,c.writeFileSync)(t,i),t}resolveConfigPath(e,t){let{[e]:n}=this.getConfig(`paths`)??{};return typeof n==`string`&&n.trim().length>0?n:t}resolveStubPath(e){return(0,l.join)(this.resolveConfigPath(`stubs`,G()),e)}makeFactory(e,t={}){let n=(0,m.str)(e.replace(/Factory$/,``)).pascal(),r=`${n}Factory`,i=t.modelName?(0,m.str)(t.modelName).pascal():n,a=this.resolveOutputExt(),o=(0,l.join)(this.resolveConfigPath(`factories`,(0,l.join)(process.cwd(),`database`,`factories`)),`${r}.${a}`),s=(0,l.join)(this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`)),`${i}.${a}`),c=t.modelImportPath??`./${this.stripKnownSourceExtension((0,l.relative)((0,l.dirname)(o),s).replace(/\\/g,`/`))}${a===`js`?`.js`:``}`,u=this.resolveStubPath(a===`js`?`factory.js.stub`:`factory.stub`);return{name:r,path:this.generateFile(u,o,{FactoryName:r,ModelName:i.toString(),ModelImportPath:c.startsWith(`.`)?c:`./${c}`},t)}}makeSeeder(e,t={}){let n=`${(0,m.str)(e.replace(/Seeder$/,``)).pascal()}Seeder`,r=this.resolveOutputExt(),i=(0,l.join)(this.resolveConfigPath(`seeders`,(0,l.join)(process.cwd(),`database`,`seeders`)),`${n}.${r}`),a=this.resolveStubPath(r===`js`?`seeder.js.stub`:`seeder.stub`);return{name:n,path:this.generateFile(a,i,{SeederName:n},t)}}makeMigration(e){let t=de(e,{directory:this.resolveConfigPath(`migrations`,(0,l.join)(process.cwd(),`database`,`migrations`)),extension:this.resolveOutputExt()});return{name:t.className,path:t.filePath}}makeModel(e,t={}){let n=(0,m.str)(e.replace(/Model$/,``)).pascal().toString(),r=`${n}`,i=(0,m.str)(n).camel().plural().toString(),a=this.resolveOutputExt(),o=(0,l.join)(this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`)),`${r}.${a}`),s=t.all||t.factory,c=t.all||t.seeder,u=t.all||t.migration,d=`${n}Factory`,f=(0,l.join)(this.resolveConfigPath(`factories`,(0,l.join)(process.cwd(),`database`,`factories`)),`${d}.${a}`),p=`./${(0,l.relative)((0,l.dirname)(o),f).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`,h=this.resolveStubPath(a===`js`?`model.js.stub`:`model.stub`),ee=this.generateFile(h,o,{ModelName:r,DelegateName:i,FactoryImport:s?`import { ${d} } from '${p}'\n`:``,FactoryLink:s?a===`js`?`\n static factoryClass = ${d}`:`\n protected static override factoryClass = ${d}`:``},t),g=this.ensurePrismaModelEntry(r,i),_={model:{name:r,path:ee},prisma:g,factory:void 0,seeder:void 0,migration:void 0};return s&&(_.factory=this.makeFactory(n,{force:t.force,modelName:r,modelImportPath:`./${(0,l.relative)((0,l.dirname)(f),o).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`})),c&&(_.seeder=this.makeSeeder(n,{force:t.force})),u&&(_.migration=this.makeMigration(`create ${i} table`)),_}ensurePrismaModelEntry(e,t){let n=(0,l.join)(process.cwd(),`prisma`,`schema.prisma`);if(!(0,c.existsSync)(n))return{path:n,updated:!1};let r=(0,c.readFileSync)(n,`utf-8`),i=D(r,t),a=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(r);return i||a?{path:n,updated:!1}:((0,c.writeFileSync)(n,O(r,{type:`createTable`,table:t,columns:[{name:`id`,type:`id`,primary:!0}]})),{path:n,updated:!0})}prismaTypeToTs(e){return e===`Int`||e===`Float`||e===`Decimal`?`number`:e===`BigInt`?`bigint`:e===`String`?`string`:e===`Boolean`?`boolean`:e===`DateTime`?`Date`:e===`Json`?`Record<string, unknown>`:e===`Bytes`?`Buffer`:`unknown`}parsePrismaModels(e){let t=[],n=/model\s+(\w+)\s*\{([\s\S]*?)\n\}/g,r=new Set([`Int`,`Float`,`Decimal`,`BigInt`,`String`,`Boolean`,`DateTime`,`Json`,`Bytes`]);for(let i of e.matchAll(n)){let e=i[1],n=i[2],a=n.match(/@@map\("([^"]+)"\)/)?.[1]??`${e.charAt(0).toLowerCase()}${e.slice(1)}s`,o=[];n.split(`
|
|
10
10
|
`).forEach(e=>{let t=e.trim();if(!t||t.startsWith(`@@`)||t.startsWith(`//`))return;let n=t.match(/^(\w+)\s+([A-Za-z]+)(\?)?\b/);if(!n)return;let i=n[2];r.has(i)&&o.push({name:n[1],type:this.prismaTypeToTs(i),optional:!!n[3]})}),t.push({name:e,table:a,fields:o})}return t}syncModelDeclarations(e,t){let n=e.split(`
|
|
11
11
|
`),r=n.findIndex(e=>/export\s+class\s+\w+\s+extends\s+Model<.+>\s*\{/.test(e));if(r<0)return{content:e,updated:!1};let i=-1,a=0;for(let e=r;e<n.length;e+=1){let t=n[e];if(a+=(t.match(/\{/g)||[]).length,a-=(t.match(/\}/g)||[]).length,a===0){i=e;break}}if(i<0)return{content:e,updated:!1};let o=n.slice(r+1,i).filter(e=>!/^\s*declare\s+\w+\??:\s*[^\n]+$/.test(e)),s=[...t.map(e=>` ${e}`),...o],c=[...n.slice(0,r+1),...s,...n.slice(i)].join(`
|
|
12
|
-
`);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let t=e.schemaPath??(0,l.join)(process.cwd(),`prisma`,`schema.prisma`),n=e.modelsDir??this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`));if(!(0,c.existsSync)(t))throw Error(`Prisma schema file not found: ${t}`);if(!(0,c.existsSync)(n))throw Error(`Models directory not found: ${n}`);let r=(0,c.readFileSync)(t,`utf-8`),i=this.parsePrismaModels(r),a=(0,c.readdirSync)(n).filter(e=>e.endsWith(`.ts`)),o=[],s=[];return a.forEach(e=>{let t=(0,l.join)(n,e),r=(0,c.readFileSync)(t,`utf-8`),a=r.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!a){s.push(t);return}let u=a[1],d=a[2],f=i.find(e=>e.table===d)??i.find(e=>e.name===u);if(!f||f.fields.length===0){s.push(t);return}let p=f.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),m=this.syncModelDeclarations(r,p);if(!m.updated){s.push(t);return}(0,c.writeFileSync)(t,m.content),o.push(t)}),{schemaPath:t,modelsDir:n,total:a.length,updated:o,skipped:s}}},
|
|
12
|
+
`);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let t=e.schemaPath??(0,l.join)(process.cwd(),`prisma`,`schema.prisma`),n=e.modelsDir??this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`));if(!(0,c.existsSync)(t))throw Error(`Prisma schema file not found: ${t}`);if(!(0,c.existsSync)(n))throw Error(`Models directory not found: ${n}`);let r=(0,c.readFileSync)(t,`utf-8`),i=this.parsePrismaModels(r),a=(0,c.readdirSync)(n).filter(e=>e.endsWith(`.ts`)),o=[],s=[];return a.forEach(e=>{let t=(0,l.join)(n,e),r=(0,c.readFileSync)(t,`utf-8`),a=r.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!a){s.push(t);return}let u=a[1],d=a[2],f=i.find(e=>e.table===d)??i.find(e=>e.name===u);if(!f||f.fields.length===0){s.push(t);return}let p=f.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),m=this.syncModelDeclarations(r,p);if(!m.updated){s.push(t);return}(0,c.writeFileSync)(t,m.content),o.push(t)}),{schemaPath:t,modelsDir:n,total:a.length,updated:o,skipped:s}}},we=class extends g.Command{signature=`init
|
|
13
13
|
{--force : Force overwrite if config file already exists (existing file will be backed up) }
|
|
14
|
-
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let e=(0,f.join)(process.cwd(),`arkormx.config.js`),{stubs:t}=
|
|
14
|
+
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let e=(0,f.join)(process.cwd(),`arkormx.config.js`),{stubs:t}=V(`paths`)??{},n=typeof t==`string`&&t.trim().length>0?t:G(),r=(0,f.join)(n,`arkormx.config.stub`),i=(0,f.join)(n,`arkorm.config.stub`),a=(0,c.existsSync)(r)?r:i;(0,c.existsSync)(e)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(e),(0,c.existsSync)(e)&&this.option(`force`)&&(0,c.copyFileSync)(e,e.replace(/\.js$/,`.backup.${Date.now()}.js`)),(0,c.existsSync)(a)||(this.error(`Error: Missing config stub at ${r} (or ${i})`),process.exit(1)),(0,c.writeFileSync)(e,(0,c.readFileSync)(a,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},Te=class extends g.Command{signature=`make:factory
|
|
15
15
|
{name : Name of the factory to create}
|
|
16
16
|
{--f|force : Overwrite existing file}
|
|
17
|
-
`;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},
|
|
17
|
+
`;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},Ee=class extends g.Command{signature=`make:migration
|
|
18
18
|
{name : Name of the migration to create}
|
|
19
|
-
`;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},
|
|
19
|
+
`;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},De=class extends g.Command{signature=`make:model
|
|
20
20
|
{name : Name of the model to create}
|
|
21
21
|
{--f|force : Overwrite existing files}
|
|
22
22
|
{--factory : Create and link a factory}
|
|
23
23
|
{--seeder : Create a seeder}
|
|
24
24
|
{--migration : Create a migration}
|
|
25
25
|
{--all : Create and link factory, seeder, and migration}
|
|
26
|
-
`;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},
|
|
26
|
+
`;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},Oe=class extends g.Command{signature=`make:seeder
|
|
27
27
|
{name : Name of the seeder to create}
|
|
28
28
|
{--f|force : Overwrite existing file}
|
|
29
|
-
`;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},
|
|
29
|
+
`;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},ke=class extends g.Command{signature=`migrate
|
|
30
30
|
{name? : Migration class or file name}
|
|
31
31
|
{--all : Run all migrations from the configured migrations directory}
|
|
32
32
|
{--deploy : Use prisma migrate deploy instead of migrate dev}
|
|
@@ -34,17 +34,17 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
34
34
|
{--skip-migrate : Skip prisma migrate command}
|
|
35
35
|
{--schema= : Explicit prisma schema path}
|
|
36
36
|
{--migration-name= : Name for prisma migrate dev}
|
|
37
|
-
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??(0,f.join)(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):(0,f.join)(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await
|
|
37
|
+
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??(0,f.join)(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):(0,f.join)(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await P(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||j([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?j([`migrate`,`deploy`],process.cwd()):j([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=(0,d.readdirSync)(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath((0,f.join)(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>(0,f.join)(e,t)).find(e=>(0,d.existsSync)(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${(0,_.pathToFileURL)((0,f.resolve)(e)).href}?arkorm_migrate=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof b:!1)}},Ae=class extends g.Command{signature=`models:sync
|
|
38
38
|
{--schema= : Path to prisma schema file}
|
|
39
39
|
{--models= : Path to models directory}
|
|
40
|
-
`;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?(0,f.resolve)(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},
|
|
40
|
+
`;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?(0,f.resolve)(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},je=class e{async call(...t){await e.runSeeders(...t)}static toSeederInstance(t){return t instanceof e?t:new t}static async runSeeders(...e){let t=e.reduce((e,t)=>Array.isArray(t)?[...e,...t]:(e.push(t),e),[]);for(let e of t)await this.toSeederInstance(e).run()}},Me=class extends g.Command{signature=`seed
|
|
41
41
|
{name? : Seeder class or file name}
|
|
42
42
|
{--all : Run all seeders in the configured seeders directory}
|
|
43
|
-
`;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??(0,f.join)(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=(0,d.readdirSync)(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath((0,f.join)(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>(0,f.join)(e,t)).find(e=>(0,d.existsSync)(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${(0,_.pathToFileURL)((0,f.resolve)(e)).href}?arkorm_seed=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof
|
|
43
|
+
`;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??(0,f.join)(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=(0,d.readdirSync)(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath((0,f.join)(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>(0,f.join)(e,t)).find(e=>(0,d.existsSync)(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${(0,_.pathToFileURL)((0,f.resolve)(e)).href}?arkorm_seed=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof je:!1)}};String.raw`
|
|
44
44
|
__/^^^^^^^^^^^^^^^^\__
|
|
45
45
|
▄▄▄/ \▄▄
|
|
46
46
|
▄██▀▀██▄ ▄▄
|
|
47
47
|
███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
|
|
48
48
|
███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
|
|
49
49
|
███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
|
|
50
|
-
`;var J=class extends te.Collection{},Me=class{amount=1;sequence=0;states=[];count(e){return this.amount=Math.max(1,Math.floor(e)),this}state(e){return this.states.push(e),this}make(e={}){let t=this.buildAttributes(e);return new this.model(t)}makeMany(e=this.amount,t={}){let n=Math.max(1,Math.floor(e));return Array.from({length:n},()=>this.make(t))}async create(e={}){let t=this.make(e);if(typeof t.save!=`function`)throw Error(`Factory model does not support save().`);return await t.save()}async createMany(e=this.amount,t={}){let n=this.makeMany(e,t);return await Promise.all(n.map(async e=>{if(typeof e.save!=`function`)throw Error(`Factory model does not support save().`);return await e.save()}))}buildAttributes(e){let t=this.sequence;this.sequence+=1;let n=this.definition(t);for(let e of this.states)n=e(n,t);return{...n,...e}}},Ne=class extends Me{model;constructor(e,t){super(),this.resolver=t,this.model=e}definition(e){return this.resolver(e)}};const Pe=(e,t)=>new Ne(e,t);var Y=class extends y{constructor(e=`No query results for the given model.`){super(e),this.name=`ModelNotFoundException`}};function Fe(e){return Object.entries(e).reduce((e,[t,n])=>(q(n)&&(e[t]=n),e),{})}function Ie(e){return Fe(e)}function Le(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}s`}var X=class{constraint=null;constrain(e){if(!this.constraint)return this.constraint=e,this;let t=this.constraint;return this.constraint=n=>{let r=t(n)??n;return e(r)??r},this}where(e){return this.constrain(t=>t.where(e))}whereKey(e,t){return this.constrain(n=>n.whereKey(e,t))}whereIn(e,t){return this.constrain(n=>n.whereIn(e,t))}orderBy(e){return this.constrain(t=>t.orderBy(e))}include(e){return this.constrain(t=>t.include(e))}with(e){return this.constrain(t=>t.with(e))}select(e){return this.constrain(t=>t.select(e))}skip(e){return this.constrain(t=>t.skip(e))}take(e){return this.constrain(t=>t.take(e))}withTrashed(){return this.constrain(e=>e.withTrashed())}onlyTrashed(){return this.constrain(e=>e.onlyTrashed())}withoutTrashed(){return this.constrain(e=>e.withoutTrashed())}scope(e,...t){return this.constrain(n=>n.scope(e,...t))}applyConstraint(e){return this.constraint?this.constraint(e)??e:e}async get(){return this.getResults()}async first(){let e=await this.getResults();return e instanceof J?e.all()[0]??null:e}},Re=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.foreignPivotKey]:e}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:t}})).get()}},ze=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.ownerKey=r}async getResults(){let e=this.parent.getAttribute(this.foreignKey);return this.applyConstraint(this.related.query().where({[this.ownerKey]:e})).first()}},Be=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).get()}},Ve=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.firstKey]:e}})).map(e=>e[this.secondLocalKey]);return this.applyConstraint(this.related.query().where({[this.secondKey]:{in:t}})).get()}},He=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).first()}},Ue=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=await this.related.getDelegate(this.throughDelegate).findFirst({where:{[this.firstKey]:e}});return t?this.applyConstraint(this.related.query().where({[this.secondKey]:t[this.secondLocalKey]})).first():null}},We=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).get()}},Ge=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).first()}},Ke=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.morphName=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=this.parent.constructor.name,n=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:n}})).get()}},Z=class e{static DEFAULT_PAGE_NAME=`page`;path;query;fragment;pageName;constructor(t={}){this.path=t.path??`/`,this.query=t.query??{},this.fragment=t.fragment??``,this.pageName=t.pageName??e.DEFAULT_PAGE_NAME}getPageName(){return this.pageName}url(e){let t=Math.max(1,e),[n,r=``]=this.path.split(`?`),i=new URLSearchParams(r);Object.entries(this.query).forEach(([e,t])=>{if(t==null){i.delete(e);return}i.set(e,String(t))}),i.set(this.pageName,String(t));let a=i.toString(),o=this.fragment.replace(/^#/,``);return!a&&!o?n:o?a?`${n}?${a}#${o}`:`${n}#${o}`:`${n}?${a}`}},Q=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=Math.max(1,Math.ceil(t/n)),o=t===0?null:(r-1)*n+1,s=t===0?null:Math.min(r*n,t);this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={total:t,perPage:n,currentPage:r,lastPage:a,from:o,to:s}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.currentPage>=this.meta.lastPage?null:this.url(this.meta.currentPage+1)}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}firstPageUrl(){return this.url(1)}lastPageUrl(){return this.url(this.meta.lastPage)}toJSON(){return{data:this.data,meta:this.meta,links:{first:this.firstPageUrl(),last:this.lastPageUrl(),prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},$=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=e.all().length,o=a===0?null:(n-1)*t+1,s=a===0?null:(o??1)+a-1;this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={perPage:t,currentPage:n,from:o,to:s,hasMorePages:r}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.hasMorePages?this.url(this.meta.currentPage+1):null}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}toJSON(){return{data:this.data,meta:this.meta,links:{prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},qe=class e{args={};eagerLoads={};includeTrashed=!1;onlyTrashedRecords=!1;randomOrderEnabled=!1;relationFilters=[];relationAggregates=[];constructor(e,t){this.delegate=e,this.model=t}where(e){return this.addLogicalWhere(`AND`,e)}orWhere(e){return this.addLogicalWhere(`OR`,e)}whereNot(e){return this.where({NOT:e})}orWhereNot(e){return this.orWhere({NOT:e})}whereNull(e){return this.where({[e]:null})}whereNotNull(e){return this.where({[e]:{not:null}})}whereBetween(e,t){let[n,r]=t;return this.where({[e]:{gte:n,lte:r}})}whereDate(e,t){let n=this.coerceDate(t),r=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),this.where({[e]:{gte:r,lt:i}})}whereMonth(e,t,n=new Date().getUTCFullYear()){let r=Math.min(12,Math.max(1,t)),i=new Date(Date.UTC(n,r-1,1)),a=new Date(Date.UTC(n,r,1));return this.where({[e]:{gte:i,lt:a}})}whereYear(e,t){let n=new Date(Date.UTC(t,0,1)),r=new Date(Date.UTC(t+1,0,1));return this.where({[e]:{gte:n,lt:r}})}whereKeyNot(e,t){return this.where({[e]:{not:t}})}orWhereIn(e,t){return this.orWhere({[e]:{in:t}})}whereNotIn(e,t){return this.where({[e]:{notIn:t}})}orWhereNotIn(e,t){return this.orWhere({[e]:{notIn:t}})}async firstWhere(e,t,n){let r=n!==void 0,i=r?t:`=`,a=r?n:t;return this.clone().where(this.buildComparisonWhere(e,i,a)).first()}addLogicalWhere(e,t){return this.args.where?(this.args.where={[e]:[this.args.where,t]},this):(this.args.where=t,this)}buildComparisonWhere(e,t,n){return t===`=`?{[e]:n}:t===`!=`?{[e]:{not:n}}:t===`>`?{[e]:{gt:n}}:t===`>=`?{[e]:{gte:n}}:t===`<`?{[e]:{lt:n}}:{[e]:{lte:n}}}coerceDate(e){let t=e instanceof Date?new Date(e.getTime()):new Date(e);if(Number.isNaN(t.getTime()))throw new y(`Invalid date value for date-based query helper.`);return t}whereKey(e,t){return this.where({[e]:t})}whereIn(e,t){return this.where({[e]:{in:t}})}orderBy(e){return this.randomOrderEnabled=!1,this.args.orderBy=e,this}inRandomOrder(){return this.randomOrderEnabled=!0,this}reorder(e,t=`asc`){return this.args.orderBy=void 0,this.randomOrderEnabled=!1,e?this.orderBy({[e]:t}):this}latest(e=`createdAt`){return this.orderBy({[e]:`desc`})}oldest(e=`createdAt`){return this.orderBy({[e]:`asc`})}include(e){return this.args.include=e,this}with(e){let t=this.normalizeWith(e),n=Object.keys(t);return this.args.include={...this.args.include||{},...n.reduce((e,t)=>(e[t]=!0,e),{})},Object.entries(t).forEach(([e,t])=>{this.eagerLoads[e]=t}),this}has(e,t=`>=`,n=1,r){return this.relationFilters.push({relation:e,callback:r,operator:t,count:n,boolean:`AND`}),this}orHas(e,t=`>=`,n=1){return this.relationFilters.push({relation:e,operator:t,count:n,boolean:`OR`}),this}doesntHave(e,t){return this.has(e,`<`,1,t)}orDoesntHave(e){return this.orHas(e,`<`,1)}whereHas(e,t,n=`>=`,r=1){return this.has(e,n,r,t)}orWhereHas(e,t,n=`>=`,r=1){return this.relationFilters.push({relation:e,callback:t,operator:n,count:r,boolean:`OR`}),this}whereDoesntHave(e,t){return this.whereHas(e,t,`<`,1)}orWhereDoesntHave(e,t){return this.orWhereHas(e,t,`<`,1)}withCount(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`count`,relation:e})}),this}withExists(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`exists`,relation:e})}),this}withSum(e,t){return this.relationAggregates.push({type:`sum`,relation:e,column:t}),this}withAvg(e,t){return this.relationAggregates.push({type:`avg`,relation:e,column:t}),this}withMin(e,t){return this.relationAggregates.push({type:`min`,relation:e,column:t}),this}withMax(e,t){return this.relationAggregates.push({type:`max`,relation:e,column:t}),this}withTrashed(){return this.includeTrashed=!0,this.onlyTrashedRecords=!1,this}onlyTrashed(){return this.onlyTrashedRecords=!0,this.includeTrashed=!1,this}withoutTrashed(){return this.includeTrashed=!1,this.onlyTrashedRecords=!1,this}scope(e,...t){let n=`scope${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=this.model.prototype?.[n];if(typeof r!=`function`)throw new y(`Scope [${e}] is not defined.`);let i=r.call(void 0,this,...t);return i&&i!==this?i:this}when(e,t,n){let r=typeof e==`function`?e():e;return r?t(this,r):n?n(this,r):this}unless(e,t,n){let r=typeof e==`function`?e():e;return r?n?n(this,r):this:t(this,r)}tap(e){return e(this),this}pipe(e){return e(this)}select(e){return this.args.select=e,this}skip(e){return this.args.skip=e,this}offset(e){return this.skip(e)}take(e){return this.args.take=e,this}limit(e){return this.take(e)}forPage(e,t=15){let n=Math.max(1,e),r=Math.max(1,t);return this.skip((n-1)*r).take(r)}async get(){let e=new WeakMap,t=await this.delegate.findMany(this.buildFindArgs()),n=this.randomOrderEnabled?this.shuffleRows(t):t,r=this.model.hydrateMany(n),i=r;if(this.hasRelationFilters())if(this.hasOrRelationFilters()&&this.args.where){let t=new Set(r.map(e=>this.getModelId(e)).filter(e=>e!=null)),n=await this.delegate.findMany({...this.args,where:this.buildSoftDeleteOnlyWhere()}),a=this.model.hydrateMany(n);i=await this.filterModelsByRelationConstraints(a,e,t)}else i=await this.filterModelsByRelationConstraints(r,e);return this.hasRelationAggregates()&&await this.applyRelationAggregates(i,e),await Promise.all(i.map(async e=>{await e.load(this.eagerLoads)})),new J(i)}async first(){if(this.hasRelationFilters()||this.hasRelationAggregates())return(await this.get()).all()[0]??null;if(this.randomOrderEnabled){let e=await this.delegate.findMany(this.buildFindArgs());if(e.length===0)return null;let t=this.shuffleRows(e)[0];if(!t)return null;let n=this.model.hydrate(t);return await n.load(this.eagerLoads),n}let e=await this.delegate.findFirst(this.buildFindArgs());if(!e)return null;let t=this.model.hydrate(e);return await t.load(this.eagerLoads),t}async firstOrFail(){let e=await this.first();if(!e)throw new Y(`Record not found.`);return e}async find(e,t=`id`){return this.where({[t]:e}).first()}async findOr(e,t,n){let r=typeof t==`string`?t:`id`,i=typeof t==`function`?t:n;if(!i)throw new y(`findOr requires a fallback callback.`);return await this.find(e,r)||i()}async value(e){let t=await this.delegate.findFirst(this.buildFindArgs());return t?t[e]??null:null}async valueOrFail(e){let t=await this.value(e);if(t==null)throw new Y(`Record not found.`);return t}async pluck(e,t){let n=await this.delegate.findMany(this.buildFindArgs());return t?new J(n.sort((e,n)=>String(e[t]).localeCompare(String(n[t]))).map(t=>t[e])):new J(n.map(t=>t[e]))}async create(e){let t=await this.delegate.create({data:e});return this.model.hydrate(t)}async update(e){let t=this.buildWhere();if(!t)throw new y(`Update requires a where clause.`);let n=await this.resolveUniqueWhere(t),r=await this.delegate.update({where:n,data:e});return this.model.hydrate(r)}async delete(){let e=this.buildWhere();if(!e)throw new y(`Delete requires a where clause.`);let t=await this.resolveUniqueWhere(e),n=await this.delegate.delete({where:t});return this.model.hydrate(n)}async count(){return this.hasRelationFilters()?(await this.get()).all().length:this.delegate.count({where:this.buildWhere()})}async exists(){return this.hasRelationFilters()?await this.count()>0:await this.delegate.findFirst(this.buildFindArgs())!=null}async doesntExist(){return!await this.exists()}async existsOr(e){return await this.exists()?!0:e()}async doesntExistOr(e){return await this.doesntExist()?!0:e()}async min(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t<e?t:e)}async max(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t>e?t:e)}async sum(e){return(await this.delegate.findMany(this.buildFindArgs())).reduce((t,n)=>{let r=n[e],i=typeof r==`number`?r:Number(r);return Number.isFinite(i)?t+i:t},0)}async avg(e){let t=(await this.delegate.findMany(this.buildFindArgs())).map(t=>{let n=t[e];return typeof n==`number`?n:Number(n)}).filter(e=>Number.isFinite(e));return t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length}whereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);return this.args.where=n.applyRawWhere(this.buildWhere(),e,t),this}orWhereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);let r=n.applyRawWhere(void 0,e,t);return this.orWhere(r)}async paginate(e=1,t=15,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,e),i=Math.max(1,t),a=(await this.get()).all(),o=(r-1)*i;return new Q(new J(a.slice(o,o+i)),a.length,i,r,n)}let r=Math.max(1,e),i=Math.max(1,t),a=await this.count();return new Q(await this.clone().skip((r-1)*i).take(i).get(),a,i,r,n)}async simplePaginate(e=15,t=1,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,t),i=Math.max(1,e),a=(await this.get()).all(),o=(r-1)*i,s=a.slice(o,o+i),c=o+i<a.length;return new $(new J(s),i,r,c,n)}let r=Math.max(1,t),i=Math.max(1,e),a=await this.clone().skip((r-1)*i).take(i+1).get(),o=a.all().length>i;return new $(o?new J(a.all().slice(0,i)):a,i,r,o,n)}clone(){let t=new e(this.delegate,this.model);return t.args.where=this.args.where,t.args.include=this.args.include,t.args.orderBy=this.args.orderBy,t.args.select=this.args.select,t.args.skip=this.args.skip,t.args.take=this.args.take,t.includeTrashed=this.includeTrashed,t.onlyTrashedRecords=this.onlyTrashedRecords,t.randomOrderEnabled=this.randomOrderEnabled,this.relationFilters.forEach(e=>{t.relationFilters.push({...e})}),this.relationAggregates.forEach(e=>{t.relationAggregates.push({...e})}),Object.entries(this.eagerLoads).forEach(([e,n])=>{t.eagerLoads[e]=n}),t}normalizeWith(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}buildWhere(){let e=this.model.getSoftDeleteConfig();if(!e.enabled||this.includeTrashed)return this.args.where;let t=this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null};return this.args.where?{AND:[this.args.where,t]}:t}buildFindArgs(){return{...this.args,where:this.buildWhere()}}async resolveUniqueWhere(e){if(this.isUniqueWhere(e))return e;let t=await this.delegate.findFirst({where:e});if(!t)throw new y(`Record not found for update/delete operation.`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`id`))throw new y(`Unable to resolve a unique identifier for update/delete operation. Include an id in the query constraints.`);return{id:n.id}}isUniqueWhere(e){return Object.keys(e).length===1&&Object.prototype.hasOwnProperty.call(e,`id`)}shuffleRows(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}hasRelationFilters(){return this.relationFilters.length>0}hasOrRelationFilters(){return this.relationFilters.some(e=>e.boolean===`OR`)}hasRelationAggregates(){return this.relationAggregates.length>0}async filterModelsByRelationConstraints(e,t,n){return(await Promise.all(e.map(async e=>{let r=null;n&&(r=n.has(this.getModelId(e)));for(let n of this.relationFilters){let i=await this.resolveRelatedCount(e,n.relation,t,n.callback),a=this.compareCount(i,n.operator,n.count);r=r==null?a:n.boolean===`AND`?r&&a:r||a}return{model:e,passes:r??!0}}))).filter(e=>e.passes).map(e=>e.model)}getModelId(e){let t=e;if(typeof t.getAttribute!=`function`)return null;let n=t.getAttribute(`id`);return typeof n==`number`||typeof n==`string`?n:null}buildSoftDeleteOnlyWhere(){let e=this.model.getSoftDeleteConfig();if(e.enabled&&!this.includeTrashed)return this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null}}async applyRelationAggregates(e,t){let n=t??new WeakMap;await Promise.all(e.map(async e=>{for(let t of this.relationAggregates){let r=await this.resolveRelatedResults(e,t.relation,n),i=Array.isArray(r)?r:r?[r]:[],a=this.buildAggregateAttributeKey(t);if(t.type===`count`){this.assignAggregate(e,a,i.length);continue}if(t.type===`exists`){this.assignAggregate(e,a,i.length>0);continue}let o=i.map(e=>e.getAttribute(t.column)).filter(e=>e!=null);if(t.type===`sum`){let t=o.reduce((e,t)=>{let n=typeof t==`number`?t:Number(t);return Number.isFinite(n)?e+n:e},0);this.assignAggregate(e,a,t);continue}if(t.type===`avg`){let t=o.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)),n=t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length;this.assignAggregate(e,a,n);continue}if(t.type===`min`){let t=o.length===0?null:o.reduce((e,t)=>t<e?t:e);this.assignAggregate(e,a,t);continue}let s=o.length===0?null:o.reduce((e,t)=>t>e?t:e);this.assignAggregate(e,a,s)}}))}async resolveRelatedCount(e,t,n,r){let i=await this.resolveRelatedResults(e,t,n,r);return Array.isArray(i)?i.length:i?1:0}async resolveRelatedResults(e,t,n,r){let i=e,a=r??`__none__`,o=n.get(i);o||(o=new Map,n.set(i,o));let s=o.get(t);s||(s=new Map,o.set(t,s));let c=s.get(a);if(c)return await c;let l=(async()=>{let n=e[t];if(typeof n!=`function`)throw new y(`Relation [${t}] is not defined on the model.`);let i=n.call(e);if(r&&typeof i.constrain==`function`&&i.constrain(e=>r(e)??e),typeof i.get==`function`){let e=await i.get();return e instanceof J?e.all():e}if(typeof i.getResults==`function`){let e=await i.getResults();return e instanceof J?e.all():e}throw new y(`Relation [${t}] does not support result resolution.`)})();return s.set(a,l),await l}compareCount(e,t,n){return t===`>=`?e>=n:t===`>`?e>n:t===`=`?e===n:t===`!=`?e!==n:t===`<=`?e<=n:e<n}buildAggregateAttributeKey(e){let t=e.relation;if(e.type===`count`)return`${t}Count`;if(e.type===`exists`)return`${t}Exists`;let n=e.column?`${e.column.charAt(0).toUpperCase()}${e.column.slice(1)}`:``;return`${t}${`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}`}${n}`}assignAggregate(e,t,n){let r=e;if(typeof r.setAttribute==`function`){r.setAttribute(t,n);return}e[t]=n}},Je=class e{static factoryClass;static client;static delegate;static softDeletes=!1;static deletedAtColumn=`deletedAt`;static globalScopes={};static eventListeners={};casts={};hidden=[];visible=[];appends=[];attributes;constructor(e={}){return this.attributes={},this.fill(e),new Proxy(this,{get:(e,t,n)=>typeof t!=`string`||t in e?Reflect.get(e,t,n):e.getAttribute(t),set:(e,t,n,r)=>typeof t!=`string`||t in e?Reflect.set(e,t,n,r):(e.setAttribute(t,n),!0)})}static setClient(e){this.client=e}static setFactory(e){this.factoryClass=e}static factory(e){let t=this.factoryClass;if(!t)throw new y(`Factory is not configured for model [${this.name}].`);let n=new t;return typeof e==`number`&&n.count(e),n}static addGlobalScope(e,t){this.ensureOwnGlobalScopes(),this.globalScopes[e]=t}static removeGlobalScope(e){this.ensureOwnGlobalScopes(),delete this.globalScopes[e]}static clearGlobalScopes(){this.globalScopes={}}static on(e,t){this.ensureOwnEventListeners(),this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e]?.push(t)}static off(e,t){if(this.ensureOwnEventListeners(),!t){delete this.eventListeners[e];return}this.eventListeners[e]=(this.eventListeners[e]||[]).filter(e=>e!==t)}static clearEventListeners(){this.eventListeners={}}static getDelegate(e){be();let t=e||this.delegate||`${(0,p.str)(this.name).camel().plural()}`,n=[t,`${(0,p.str)(t).camel()}`,`${(0,p.str)(t).singular()}`,`${(0,p.str)(t).camel().singular()}`],r=xe(),i=n.map(e=>this.client?.[e]??r?.[e]).find(e=>q(e));if(!i)throw new y(`Database delegate [${t}] is not configured.`);return i}static query(){let e=new qe(this.getDelegate(),this),t=this;return t.ensureOwnGlobalScopes(),Object.values(t.globalScopes).forEach(t=>{let n=t(e);n&&n!==e&&(e=n)}),e}static withTrashed(){return this.query().withTrashed()}static onlyTrashed(){return this.query().onlyTrashed()}static scope(e,...t){return this.query().scope(e,...t)}static getSoftDeleteConfig(){return{enabled:this.softDeletes,column:this.deletedAtColumn}}static hydrate(e){return new this(e)}static hydrateMany(e){return e.map(e=>new this(e))}fill(e){return Object.entries(e).forEach(([e,t])=>{this.setAttribute(e,t)}),this}getAttribute(e){let t=this.resolveGetMutator(e),n=this.casts[e],r=this.attributes[e];return n&&(r=v(n).get(r)),t?t.call(this,r):r}setAttribute(e,t){let n=this.resolveSetMutator(e),r=this.casts[e],i=t;return n&&(i=n.call(this,i)),r&&(i=v(r).set(i)),this.attributes[e]=i,this}async save(){let t=this.getAttribute(`id`),n=this.getRawAttributes(),r=this.constructor;if(t==null){await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`creating`,this);let t=await r.query().create(n);return this.fill(t.getRawAttributes()),await e.dispatchEvent(r,`created`,this),await e.dispatchEvent(r,`saved`,this),this}await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`updating`,this);let i=await r.query().where({id:t}).update(n);return this.fill(i.getRawAttributes()),await e.dispatchEvent(r,`updated`,this),await e.dispatchEvent(r,`saved`,this),this}async delete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`deleting`,this);let r=n.getSoftDeleteConfig();if(r.enabled){let i=await n.query().where({id:t}).update({[r.column]:new Date});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}let i=await n.query().where({id:t}).delete();return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}async forceDelete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot force delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`forceDeleting`,this),await e.dispatchEvent(n,`deleting`,this);let r=await n.query().withTrashed().where({id:t}).delete();return this.fill(r.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),await e.dispatchEvent(n,`forceDeleted`,this),this}async restore(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot restore a model without an id.`);let n=this.constructor,r=n.getSoftDeleteConfig();if(!r.enabled)return this;await e.dispatchEvent(n,`restoring`,this);let i=await n.query().withTrashed().where({id:t}).update({[r.column]:null});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`restored`,this),this}async load(e){let t=this.normalizeRelationMap(e);return await Promise.all(Object.entries(t).map(async([e,t])=>{let n=this[e];if(typeof n!=`function`)return;let r=n.call(this);t&&r.constrain(t);let i=await r.getResults();this.attributes[e]=i})),this}getRawAttributes(){return{...this.attributes}}toObject(){let e=(this.visible.length>0?this.visible:Object.keys(this.attributes).filter(e=>!this.hidden.includes(e))).reduce((e,t)=>{let n=this.getAttribute(t);return n instanceof Date&&(n=n.toISOString()),e[t]=n,e},{});return this.appends.forEach(t=>{e[t]=this.getAttribute(t)}),e}toJSON(){return this.toObject()}hasOne(e,t,n=`id`){return new He(this,e,t,n)}hasMany(e,t,n=`id`){return new Be(this,e,t,n)}belongsTo(e,t,n=`id`){return new ze(this,e,t,n)}belongsToMany(e,t,n,r,i=`id`,a=`id`){return new Re(this,e,t,n,r,i,a)}hasOneThrough(e,t,n,r,i=`id`,a=`id`){return new Ue(this,e,t,n,r,i,a)}hasManyThrough(e,t,n,r,i=`id`,a=`id`){return new Ve(this,e,t,n,r,i,a)}morphOne(e,t,n=`id`){return new Ge(this,e,t,n)}morphMany(e,t,n=`id`){return new We(this,e,t,n)}morphToMany(e,t,n,r,i=`id`,a=`id`){return new Ke(this,e,t,n,r,i,a)}resolveGetMutator(e){let t=`get${(0,p.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}resolveSetMutator(e){let t=`set${(0,p.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}static ensureOwnGlobalScopes(){Object.prototype.hasOwnProperty.call(this,`globalScopes`)||(this.globalScopes={...this.globalScopes||{}})}static ensureOwnEventListeners(){Object.prototype.hasOwnProperty.call(this,`eventListeners`)||(this.eventListeners={...this.eventListeners||{}})}static async dispatchEvent(e,t,n){e.ensureOwnEventListeners();let r=e.eventListeners[t]||[];for(let e of r)await e(n)}normalizeRelationMap(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}};exports.ArkormCollection=J,exports.ArkormException=y,exports.CliApp=Se,exports.InitCommand=Ce,exports.InlineFactory=Ne,exports.LengthAwarePaginator=Q,exports.MakeFactoryCommand=we,exports.MakeMigrationCommand=Te,exports.MakeModelCommand=Ee,exports.MakeSeederCommand=De,exports.MigrateCommand=Oe,exports.Migration=x,exports.Model=Je,exports.ModelFactory=Me,exports.ModelNotFoundException=Y,exports.ModelsSyncCommand=ke,exports.PRISMA_MODEL_REGEX=S,exports.Paginator=$,exports.QueryBuilder=qe,exports.SchemaBuilder=re,exports.SeedCommand=je,exports.Seeder=Ae,exports.TableBuilder=b,exports.URLDriver=Z,exports.applyAlterTableOperation=oe,exports.applyCreateTableOperation=O,exports.applyDropTableOperation=se,exports.applyMigrationToPrismaSchema=N,exports.applyOperationsToPrismaSchema=ce,exports.buildFieldLine=T,exports.buildMigrationSource=M,exports.buildModelBlock=E,exports.configureArkormRuntime=V,exports.createMigrationTimestamp=j,exports.createPrismaAdapter=Fe,exports.createPrismaDelegateMap=Ie,exports.defineConfig=ge,exports.defineFactory=Pe,exports.ensureArkormConfigLoading=be,exports.escapeRegex=w,exports.findModelBlock=D,exports.formatDefaultValue=ae,exports.generateMigrationFile=de,exports.getDefaultStubsPath=G,exports.getMigrationPlan=fe,exports.getRuntimePaginationURLDriverFactory=K,exports.getRuntimePrismaClient=xe,exports.getUserConfig=B,exports.inferDelegateName=Le,exports.isDelegateLike=q,exports.loadArkormConfig=W,exports.pad=A,exports.resetArkormRuntimeForTests=_e,exports.resolveCast=v,exports.resolveMigrationClassName=le,exports.resolvePrismaType=ie,exports.runMigrationWithPrisma=pe,exports.runPrismaCommand=k,exports.toMigrationFileSlug=ue,exports.toModelName=C;
|
|
50
|
+
`;var J=class extends te.Collection{},Ne=class{amount=1;sequence=0;states=[];count(e){return this.amount=Math.max(1,Math.floor(e)),this}state(e){return this.states.push(e),this}make(e={}){let t=this.buildAttributes(e);return new this.model(t)}makeMany(e=this.amount,t={}){let n=Math.max(1,Math.floor(e));return Array.from({length:n},()=>this.make(t))}async create(e={}){let t=this.make(e);if(typeof t.save!=`function`)throw Error(`Factory model does not support save().`);return await t.save()}async createMany(e=this.amount,t={}){let n=this.makeMany(e,t);return await Promise.all(n.map(async e=>{if(typeof e.save!=`function`)throw Error(`Factory model does not support save().`);return await e.save()}))}buildAttributes(e){let t=this.sequence;this.sequence+=1;let n=this.definition(t);for(let e of this.states)n=e(n,t);return{...n,...e}}},Pe=class extends Ne{model;constructor(e,t){super(),this.resolver=t,this.model=e}definition(e){return this.resolver(e)}};const Fe=(e,t)=>new Pe(e,t);var Y=class extends y{constructor(e=`No query results for the given model.`){super(e),this.name=`ModelNotFoundException`}};function Ie(e){return Object.entries(e).reduce((e,[t,n])=>(q(n)&&(e[t]=n),e),{})}function Le(e){return Ie(e)}function Re(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}s`}var X=class{constraint=null;constrain(e){if(!this.constraint)return this.constraint=e,this;let t=this.constraint;return this.constraint=n=>{let r=t(n)??n;return e(r)??r},this}where(e){return this.constrain(t=>t.where(e))}whereKey(e,t){return this.constrain(n=>n.whereKey(e,t))}whereIn(e,t){return this.constrain(n=>n.whereIn(e,t))}orderBy(e){return this.constrain(t=>t.orderBy(e))}include(e){return this.constrain(t=>t.include(e))}with(e){return this.constrain(t=>t.with(e))}select(e){return this.constrain(t=>t.select(e))}skip(e){return this.constrain(t=>t.skip(e))}take(e){return this.constrain(t=>t.take(e))}withTrashed(){return this.constrain(e=>e.withTrashed())}onlyTrashed(){return this.constrain(e=>e.onlyTrashed())}withoutTrashed(){return this.constrain(e=>e.withoutTrashed())}scope(e,...t){return this.constrain(n=>n.scope(e,...t))}applyConstraint(e){return this.constraint?this.constraint(e)??e:e}async get(){return this.getResults()}async first(){let e=await this.getResults();return e instanceof J?e.all()[0]??null:e}},ze=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.foreignPivotKey]:e}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:t}})).get()}},Be=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.ownerKey=r}async getResults(){let e=this.parent.getAttribute(this.foreignKey);return this.applyConstraint(this.related.query().where({[this.ownerKey]:e})).first()}},Ve=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).get()}},He=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.firstKey]:e}})).map(e=>e[this.secondLocalKey]);return this.applyConstraint(this.related.query().where({[this.secondKey]:{in:t}})).get()}},Ue=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).first()}},We=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=await this.related.getDelegate(this.throughDelegate).findFirst({where:{[this.firstKey]:e}});return t?this.applyConstraint(this.related.query().where({[this.secondKey]:t[this.secondLocalKey]})).first():null}},Ge=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).get()}},Ke=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).first()}},qe=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.morphName=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=this.parent.constructor.name,n=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:n}})).get()}},Z=class e{static DEFAULT_PAGE_NAME=`page`;path;query;fragment;pageName;constructor(t={}){this.path=t.path??`/`,this.query=t.query??{},this.fragment=t.fragment??``,this.pageName=t.pageName??e.DEFAULT_PAGE_NAME}getPageName(){return this.pageName}url(e){let t=Math.max(1,e),[n,r=``]=this.path.split(`?`),i=new URLSearchParams(r);Object.entries(this.query).forEach(([e,t])=>{if(t==null){i.delete(e);return}i.set(e,String(t))}),i.set(this.pageName,String(t));let a=i.toString(),o=this.fragment.replace(/^#/,``);return!a&&!o?n:o?a?`${n}?${a}#${o}`:`${n}#${o}`:`${n}?${a}`}},Q=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=Math.max(1,Math.ceil(t/n)),o=t===0?null:(r-1)*n+1,s=t===0?null:Math.min(r*n,t);this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={total:t,perPage:n,currentPage:r,lastPage:a,from:o,to:s}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.currentPage>=this.meta.lastPage?null:this.url(this.meta.currentPage+1)}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}firstPageUrl(){return this.url(1)}lastPageUrl(){return this.url(this.meta.lastPage)}toJSON(){return{data:this.data,meta:this.meta,links:{first:this.firstPageUrl(),last:this.lastPageUrl(),prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},$=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=e.all().length,o=a===0?null:(n-1)*t+1,s=a===0?null:(o??1)+a-1;this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={perPage:t,currentPage:n,from:o,to:s,hasMorePages:r}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.hasMorePages?this.url(this.meta.currentPage+1):null}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}toJSON(){return{data:this.data,meta:this.meta,links:{prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},Je=class e{args={};eagerLoads={};includeTrashed=!1;onlyTrashedRecords=!1;randomOrderEnabled=!1;relationFilters=[];relationAggregates=[];constructor(e,t){this.delegate=e,this.model=t}where(e){return this.addLogicalWhere(`AND`,e)}orWhere(e){return this.addLogicalWhere(`OR`,e)}whereNot(e){return this.where({NOT:e})}orWhereNot(e){return this.orWhere({NOT:e})}whereNull(e){return this.where({[e]:null})}whereNotNull(e){return this.where({[e]:{not:null}})}whereBetween(e,t){let[n,r]=t;return this.where({[e]:{gte:n,lte:r}})}whereDate(e,t){let n=this.coerceDate(t),r=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),this.where({[e]:{gte:r,lt:i}})}whereMonth(e,t,n=new Date().getUTCFullYear()){let r=Math.min(12,Math.max(1,t)),i=new Date(Date.UTC(n,r-1,1)),a=new Date(Date.UTC(n,r,1));return this.where({[e]:{gte:i,lt:a}})}whereYear(e,t){let n=new Date(Date.UTC(t,0,1)),r=new Date(Date.UTC(t+1,0,1));return this.where({[e]:{gte:n,lt:r}})}whereKeyNot(e,t){return this.where({[e]:{not:t}})}orWhereIn(e,t){return this.orWhere({[e]:{in:t}})}whereNotIn(e,t){return this.where({[e]:{notIn:t}})}orWhereNotIn(e,t){return this.orWhere({[e]:{notIn:t}})}async firstWhere(e,t,n){let r=n!==void 0,i=r?t:`=`,a=r?n:t;return this.clone().where(this.buildComparisonWhere(e,i,a)).first()}addLogicalWhere(e,t){return this.args.where?(this.args.where={[e]:[this.args.where,t]},this):(this.args.where=t,this)}buildComparisonWhere(e,t,n){return t===`=`?{[e]:n}:t===`!=`?{[e]:{not:n}}:t===`>`?{[e]:{gt:n}}:t===`>=`?{[e]:{gte:n}}:t===`<`?{[e]:{lt:n}}:{[e]:{lte:n}}}coerceDate(e){let t=e instanceof Date?new Date(e.getTime()):new Date(e);if(Number.isNaN(t.getTime()))throw new y(`Invalid date value for date-based query helper.`);return t}whereKey(e,t){return this.where({[e]:t})}whereIn(e,t){return this.where({[e]:{in:t}})}orderBy(e){return this.randomOrderEnabled=!1,this.args.orderBy=e,this}inRandomOrder(){return this.randomOrderEnabled=!0,this}reorder(e,t=`asc`){return this.args.orderBy=void 0,this.randomOrderEnabled=!1,e?this.orderBy({[e]:t}):this}latest(e=`createdAt`){return this.orderBy({[e]:`desc`})}oldest(e=`createdAt`){return this.orderBy({[e]:`asc`})}include(e){return this.args.include=e,this}with(e){let t=this.normalizeWith(e),n=Object.keys(t);return this.args.include={...this.args.include||{},...n.reduce((e,t)=>(e[t]=!0,e),{})},Object.entries(t).forEach(([e,t])=>{this.eagerLoads[e]=t}),this}has(e,t=`>=`,n=1,r){return this.relationFilters.push({relation:e,callback:r,operator:t,count:n,boolean:`AND`}),this}orHas(e,t=`>=`,n=1){return this.relationFilters.push({relation:e,operator:t,count:n,boolean:`OR`}),this}doesntHave(e,t){return this.has(e,`<`,1,t)}orDoesntHave(e){return this.orHas(e,`<`,1)}whereHas(e,t,n=`>=`,r=1){return this.has(e,n,r,t)}orWhereHas(e,t,n=`>=`,r=1){return this.relationFilters.push({relation:e,callback:t,operator:n,count:r,boolean:`OR`}),this}whereDoesntHave(e,t){return this.whereHas(e,t,`<`,1)}orWhereDoesntHave(e,t){return this.orWhereHas(e,t,`<`,1)}withCount(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`count`,relation:e})}),this}withExists(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`exists`,relation:e})}),this}withSum(e,t){return this.relationAggregates.push({type:`sum`,relation:e,column:t}),this}withAvg(e,t){return this.relationAggregates.push({type:`avg`,relation:e,column:t}),this}withMin(e,t){return this.relationAggregates.push({type:`min`,relation:e,column:t}),this}withMax(e,t){return this.relationAggregates.push({type:`max`,relation:e,column:t}),this}withTrashed(){return this.includeTrashed=!0,this.onlyTrashedRecords=!1,this}onlyTrashed(){return this.onlyTrashedRecords=!0,this.includeTrashed=!1,this}withoutTrashed(){return this.includeTrashed=!1,this.onlyTrashedRecords=!1,this}scope(e,...t){let n=`scope${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=this.model.prototype?.[n];if(typeof r!=`function`)throw new y(`Scope [${e}] is not defined.`);let i=r.call(void 0,this,...t);return i&&i!==this?i:this}when(e,t,n){let r=typeof e==`function`?e():e;return r?t(this,r):n?n(this,r):this}unless(e,t,n){let r=typeof e==`function`?e():e;return r?n?n(this,r):this:t(this,r)}tap(e){return e(this),this}pipe(e){return e(this)}select(e){return this.args.select=e,this}skip(e){return this.args.skip=e,this}offset(e){return this.skip(e)}take(e){return this.args.take=e,this}limit(e){return this.take(e)}forPage(e,t=15){let n=Math.max(1,e),r=Math.max(1,t);return this.skip((n-1)*r).take(r)}async get(){let e=new WeakMap,t=await this.delegate.findMany(this.buildFindArgs()),n=this.randomOrderEnabled?this.shuffleRows(t):t,r=this.model.hydrateMany(n),i=r;if(this.hasRelationFilters())if(this.hasOrRelationFilters()&&this.args.where){let t=new Set(r.map(e=>this.getModelId(e)).filter(e=>e!=null)),n=await this.delegate.findMany({...this.args,where:this.buildSoftDeleteOnlyWhere()}),a=this.model.hydrateMany(n);i=await this.filterModelsByRelationConstraints(a,e,t)}else i=await this.filterModelsByRelationConstraints(r,e);return this.hasRelationAggregates()&&await this.applyRelationAggregates(i,e),await Promise.all(i.map(async e=>{await e.load(this.eagerLoads)})),new J(i)}async first(){if(this.hasRelationFilters()||this.hasRelationAggregates())return(await this.get()).all()[0]??null;if(this.randomOrderEnabled){let e=await this.delegate.findMany(this.buildFindArgs());if(e.length===0)return null;let t=this.shuffleRows(e)[0];if(!t)return null;let n=this.model.hydrate(t);return await n.load(this.eagerLoads),n}let e=await this.delegate.findFirst(this.buildFindArgs());if(!e)return null;let t=this.model.hydrate(e);return await t.load(this.eagerLoads),t}async firstOrFail(){let e=await this.first();if(!e)throw new Y(`Record not found.`);return e}async find(e,t=`id`){return this.where({[t]:e}).first()}async findOr(e,t,n){let r=typeof t==`string`?t:`id`,i=typeof t==`function`?t:n;if(!i)throw new y(`findOr requires a fallback callback.`);return await this.find(e,r)||i()}async value(e){let t=await this.delegate.findFirst(this.buildFindArgs());return t?t[e]??null:null}async valueOrFail(e){let t=await this.value(e);if(t==null)throw new Y(`Record not found.`);return t}async pluck(e,t){let n=await this.delegate.findMany(this.buildFindArgs());return t?new J(n.sort((e,n)=>String(e[t]).localeCompare(String(n[t]))).map(t=>t[e])):new J(n.map(t=>t[e]))}async create(e){let t=await this.delegate.create({data:e});return this.model.hydrate(t)}async update(e){let t=this.buildWhere();if(!t)throw new y(`Update requires a where clause.`);let n=await this.resolveUniqueWhere(t),r=await this.delegate.update({where:n,data:e});return this.model.hydrate(r)}async delete(){let e=this.buildWhere();if(!e)throw new y(`Delete requires a where clause.`);let t=await this.resolveUniqueWhere(e),n=await this.delegate.delete({where:t});return this.model.hydrate(n)}async count(){return this.hasRelationFilters()?(await this.get()).all().length:this.delegate.count({where:this.buildWhere()})}async exists(){return this.hasRelationFilters()?await this.count()>0:await this.delegate.findFirst(this.buildFindArgs())!=null}async doesntExist(){return!await this.exists()}async existsOr(e){return await this.exists()?!0:e()}async doesntExistOr(e){return await this.doesntExist()?!0:e()}async min(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t<e?t:e)}async max(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t>e?t:e)}async sum(e){return(await this.delegate.findMany(this.buildFindArgs())).reduce((t,n)=>{let r=n[e],i=typeof r==`number`?r:Number(r);return Number.isFinite(i)?t+i:t},0)}async avg(e){let t=(await this.delegate.findMany(this.buildFindArgs())).map(t=>{let n=t[e];return typeof n==`number`?n:Number(n)}).filter(e=>Number.isFinite(e));return t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length}whereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);return this.args.where=n.applyRawWhere(this.buildWhere(),e,t),this}orWhereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);let r=n.applyRawWhere(void 0,e,t);return this.orWhere(r)}async paginate(e=1,t=15,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,e),i=Math.max(1,t),a=(await this.get()).all(),o=(r-1)*i;return new Q(new J(a.slice(o,o+i)),a.length,i,r,n)}let r=Math.max(1,e),i=Math.max(1,t),a=await this.count();return new Q(await this.clone().skip((r-1)*i).take(i).get(),a,i,r,n)}async simplePaginate(e=15,t=1,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,t),i=Math.max(1,e),a=(await this.get()).all(),o=(r-1)*i,s=a.slice(o,o+i),c=o+i<a.length;return new $(new J(s),i,r,c,n)}let r=Math.max(1,t),i=Math.max(1,e),a=await this.clone().skip((r-1)*i).take(i+1).get(),o=a.all().length>i;return new $(o?new J(a.all().slice(0,i)):a,i,r,o,n)}clone(){let t=new e(this.delegate,this.model);return t.args.where=this.args.where,t.args.include=this.args.include,t.args.orderBy=this.args.orderBy,t.args.select=this.args.select,t.args.skip=this.args.skip,t.args.take=this.args.take,t.includeTrashed=this.includeTrashed,t.onlyTrashedRecords=this.onlyTrashedRecords,t.randomOrderEnabled=this.randomOrderEnabled,this.relationFilters.forEach(e=>{t.relationFilters.push({...e})}),this.relationAggregates.forEach(e=>{t.relationAggregates.push({...e})}),Object.entries(this.eagerLoads).forEach(([e,n])=>{t.eagerLoads[e]=n}),t}normalizeWith(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}buildWhere(){let e=this.model.getSoftDeleteConfig();if(!e.enabled||this.includeTrashed)return this.args.where;let t=this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null};return this.args.where?{AND:[this.args.where,t]}:t}buildFindArgs(){return{...this.args,where:this.buildWhere()}}async resolveUniqueWhere(e){if(this.isUniqueWhere(e))return e;let t=await this.delegate.findFirst({where:e});if(!t)throw new y(`Record not found for update/delete operation.`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`id`))throw new y(`Unable to resolve a unique identifier for update/delete operation. Include an id in the query constraints.`);return{id:n.id}}isUniqueWhere(e){return Object.keys(e).length===1&&Object.prototype.hasOwnProperty.call(e,`id`)}shuffleRows(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}hasRelationFilters(){return this.relationFilters.length>0}hasOrRelationFilters(){return this.relationFilters.some(e=>e.boolean===`OR`)}hasRelationAggregates(){return this.relationAggregates.length>0}async filterModelsByRelationConstraints(e,t,n){return(await Promise.all(e.map(async e=>{let r=null;n&&(r=n.has(this.getModelId(e)));for(let n of this.relationFilters){let i=await this.resolveRelatedCount(e,n.relation,t,n.callback),a=this.compareCount(i,n.operator,n.count);r=r==null?a:n.boolean===`AND`?r&&a:r||a}return{model:e,passes:r??!0}}))).filter(e=>e.passes).map(e=>e.model)}getModelId(e){let t=e;if(typeof t.getAttribute!=`function`)return null;let n=t.getAttribute(`id`);return typeof n==`number`||typeof n==`string`?n:null}buildSoftDeleteOnlyWhere(){let e=this.model.getSoftDeleteConfig();if(e.enabled&&!this.includeTrashed)return this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null}}async applyRelationAggregates(e,t){let n=t??new WeakMap;await Promise.all(e.map(async e=>{for(let t of this.relationAggregates){let r=await this.resolveRelatedResults(e,t.relation,n),i=Array.isArray(r)?r:r?[r]:[],a=this.buildAggregateAttributeKey(t);if(t.type===`count`){this.assignAggregate(e,a,i.length);continue}if(t.type===`exists`){this.assignAggregate(e,a,i.length>0);continue}let o=i.map(e=>e.getAttribute(t.column)).filter(e=>e!=null);if(t.type===`sum`){let t=o.reduce((e,t)=>{let n=typeof t==`number`?t:Number(t);return Number.isFinite(n)?e+n:e},0);this.assignAggregate(e,a,t);continue}if(t.type===`avg`){let t=o.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)),n=t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length;this.assignAggregate(e,a,n);continue}if(t.type===`min`){let t=o.length===0?null:o.reduce((e,t)=>t<e?t:e);this.assignAggregate(e,a,t);continue}let s=o.length===0?null:o.reduce((e,t)=>t>e?t:e);this.assignAggregate(e,a,s)}}))}async resolveRelatedCount(e,t,n,r){let i=await this.resolveRelatedResults(e,t,n,r);return Array.isArray(i)?i.length:i?1:0}async resolveRelatedResults(e,t,n,r){let i=e,a=r??`__none__`,o=n.get(i);o||(o=new Map,n.set(i,o));let s=o.get(t);s||(s=new Map,o.set(t,s));let c=s.get(a);if(c)return await c;let l=(async()=>{let n=e[t];if(typeof n!=`function`)throw new y(`Relation [${t}] is not defined on the model.`);let i=n.call(e);if(r&&typeof i.constrain==`function`&&i.constrain(e=>r(e)??e),typeof i.get==`function`){let e=await i.get();return e instanceof J?e.all():e}if(typeof i.getResults==`function`){let e=await i.getResults();return e instanceof J?e.all():e}throw new y(`Relation [${t}] does not support result resolution.`)})();return s.set(a,l),await l}compareCount(e,t,n){return t===`>=`?e>=n:t===`>`?e>n:t===`=`?e===n:t===`!=`?e!==n:t===`<=`?e<=n:e<n}buildAggregateAttributeKey(e){let t=e.relation;if(e.type===`count`)return`${t}Count`;if(e.type===`exists`)return`${t}Exists`;let n=e.column?`${e.column.charAt(0).toUpperCase()}${e.column.slice(1)}`:``;return`${t}${`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}`}${n}`}assignAggregate(e,t,n){let r=e;if(typeof r.setAttribute==`function`){r.setAttribute(t,n);return}e[t]=n}},Ye=class e{static factoryClass;static client;static delegate;static softDeletes=!1;static deletedAtColumn=`deletedAt`;static globalScopes={};static eventListeners={};casts={};hidden=[];visible=[];appends=[];attributes;constructor(e={}){return this.attributes={},this.fill(e),new Proxy(this,{get:(e,t,n)=>typeof t!=`string`||t in e?Reflect.get(e,t,n):e.getAttribute(t),set:(e,t,n,r)=>typeof t!=`string`||t in e?Reflect.set(e,t,n,r):(e.setAttribute(t,n),!0)})}static setClient(e){this.client=e}static setFactory(e){this.factoryClass=e}static factory(e){let t=this.factoryClass;if(!t)throw new y(`Factory is not configured for model [${this.name}].`);let n=new t;return typeof e==`number`&&n.count(e),n}static addGlobalScope(e,t){this.ensureOwnGlobalScopes(),this.globalScopes[e]=t}static removeGlobalScope(e){this.ensureOwnGlobalScopes(),delete this.globalScopes[e]}static clearGlobalScopes(){this.globalScopes={}}static on(e,t){this.ensureOwnEventListeners(),this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e]?.push(t)}static off(e,t){if(this.ensureOwnEventListeners(),!t){delete this.eventListeners[e];return}this.eventListeners[e]=(this.eventListeners[e]||[]).filter(e=>e!==t)}static clearEventListeners(){this.eventListeners={}}static getDelegate(e){xe();let t=e||this.delegate||`${(0,m.str)(this.name).camel().plural()}`,n=[t,`${(0,m.str)(t).camel()}`,`${(0,m.str)(t).singular()}`,`${(0,m.str)(t).camel().singular()}`],r=Se(),i=n.map(e=>this.client?.[e]??r?.[e]).find(e=>q(e));if(!i)throw new y(`Database delegate [${t}] is not configured.`);return i}static query(){let e=new Je(this.getDelegate(),this),t=this;return t.ensureOwnGlobalScopes(),Object.values(t.globalScopes).forEach(t=>{let n=t(e);n&&n!==e&&(e=n)}),e}static withTrashed(){return this.query().withTrashed()}static onlyTrashed(){return this.query().onlyTrashed()}static scope(e,...t){return this.query().scope(e,...t)}static getSoftDeleteConfig(){return{enabled:this.softDeletes,column:this.deletedAtColumn}}static hydrate(e){return new this(e)}static hydrateMany(e){return e.map(e=>new this(e))}fill(e){return Object.entries(e).forEach(([e,t])=>{this.setAttribute(e,t)}),this}getAttribute(e){let t=this.resolveGetMutator(e),n=this.casts[e],r=this.attributes[e];return n&&(r=v(n).get(r)),t?t.call(this,r):r}setAttribute(e,t){let n=this.resolveSetMutator(e),r=this.casts[e],i=t;return n&&(i=n.call(this,i)),r&&(i=v(r).set(i)),this.attributes[e]=i,this}async save(){let t=this.getAttribute(`id`),n=this.getRawAttributes(),r=this.constructor;if(t==null){await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`creating`,this);let t=await r.query().create(n);return this.fill(t.getRawAttributes()),await e.dispatchEvent(r,`created`,this),await e.dispatchEvent(r,`saved`,this),this}await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`updating`,this);let i=await r.query().where({id:t}).update(n);return this.fill(i.getRawAttributes()),await e.dispatchEvent(r,`updated`,this),await e.dispatchEvent(r,`saved`,this),this}async delete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`deleting`,this);let r=n.getSoftDeleteConfig();if(r.enabled){let i=await n.query().where({id:t}).update({[r.column]:new Date});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}let i=await n.query().where({id:t}).delete();return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}async forceDelete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot force delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`forceDeleting`,this),await e.dispatchEvent(n,`deleting`,this);let r=await n.query().withTrashed().where({id:t}).delete();return this.fill(r.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),await e.dispatchEvent(n,`forceDeleted`,this),this}async restore(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot restore a model without an id.`);let n=this.constructor,r=n.getSoftDeleteConfig();if(!r.enabled)return this;await e.dispatchEvent(n,`restoring`,this);let i=await n.query().withTrashed().where({id:t}).update({[r.column]:null});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`restored`,this),this}async load(e){let t=this.normalizeRelationMap(e);return await Promise.all(Object.entries(t).map(async([e,t])=>{let n=this[e];if(typeof n!=`function`)return;let r=n.call(this);t&&r.constrain(t);let i=await r.getResults();this.attributes[e]=i})),this}getRawAttributes(){return{...this.attributes}}toObject(){let e=(this.visible.length>0?this.visible:Object.keys(this.attributes).filter(e=>!this.hidden.includes(e))).reduce((e,t)=>{let n=this.getAttribute(t);return n instanceof Date&&(n=n.toISOString()),e[t]=n,e},{});return this.appends.forEach(t=>{e[t]=this.getAttribute(t)}),e}toJSON(){return this.toObject()}hasOne(e,t,n=`id`){return new Ue(this,e,t,n)}hasMany(e,t,n=`id`){return new Ve(this,e,t,n)}belongsTo(e,t,n=`id`){return new Be(this,e,t,n)}belongsToMany(e,t,n,r,i=`id`,a=`id`){return new ze(this,e,t,n,r,i,a)}hasOneThrough(e,t,n,r,i=`id`,a=`id`){return new We(this,e,t,n,r,i,a)}hasManyThrough(e,t,n,r,i=`id`,a=`id`){return new He(this,e,t,n,r,i,a)}morphOne(e,t,n=`id`){return new Ke(this,e,t,n)}morphMany(e,t,n=`id`){return new Ge(this,e,t,n)}morphToMany(e,t,n,r,i=`id`,a=`id`){return new qe(this,e,t,n,r,i,a)}resolveGetMutator(e){let t=`get${(0,m.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}resolveSetMutator(e){let t=`set${(0,m.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}static ensureOwnGlobalScopes(){Object.prototype.hasOwnProperty.call(this,`globalScopes`)||(this.globalScopes={...this.globalScopes||{}})}static ensureOwnEventListeners(){Object.prototype.hasOwnProperty.call(this,`eventListeners`)||(this.eventListeners={...this.eventListeners||{}})}static async dispatchEvent(e,t,n){e.ensureOwnEventListeners();let r=e.eventListeners[t]||[];for(let e of r)await e(n)}normalizeRelationMap(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}};exports.ArkormCollection=J,exports.ArkormException=y,exports.CliApp=Ce,exports.InitCommand=we,exports.InlineFactory=Pe,exports.LengthAwarePaginator=Q,exports.MakeFactoryCommand=Te,exports.MakeMigrationCommand=Ee,exports.MakeModelCommand=De,exports.MakeSeederCommand=Oe,exports.MigrateCommand=ke,exports.Migration=b,exports.Model=Ye,exports.ModelFactory=Ne,exports.ModelNotFoundException=Y,exports.ModelsSyncCommand=Ae,exports.PRISMA_MODEL_REGEX=ie,exports.Paginator=$,exports.QueryBuilder=Je,exports.SchemaBuilder=re,exports.SeedCommand=Me,exports.Seeder=je,exports.TableBuilder=x,exports.URLDriver=Z,exports.applyAlterTableOperation=k,exports.applyCreateTableOperation=O,exports.applyDropTableOperation=A,exports.applyMigrationToPrismaSchema=P,exports.applyOperationsToPrismaSchema=se,exports.buildFieldLine=T,exports.buildIndexLine=E,exports.buildMigrationSource=ue,exports.buildModelBlock=oe,exports.configureArkormRuntime=H,exports.createMigrationTimestamp=N,exports.createPrismaAdapter=Ie,exports.createPrismaDelegateMap=Le,exports.defineConfig=ge,exports.defineFactory=Fe,exports.ensureArkormConfigLoading=xe,exports.escapeRegex=C,exports.findModelBlock=D,exports.formatDefaultValue=w,exports.generateMigrationFile=de,exports.getDefaultStubsPath=G,exports.getMigrationPlan=fe,exports.getRuntimePaginationURLDriverFactory=K,exports.getRuntimePrismaClient=Se,exports.getUserConfig=V,exports.inferDelegateName=Re,exports.isDelegateLike=q,exports.loadArkormConfig=W,exports.pad=M,exports.resetArkormRuntimeForTests=_e,exports.resolveCast=v,exports.resolveMigrationClassName=ce,exports.resolvePrismaType=ae,exports.runMigrationWithPrisma=pe,exports.runPrismaCommand=j,exports.toMigrationFileSlug=le,exports.toModelName=S;
|
package/dist/index.d.cts
CHANGED
|
@@ -11,25 +11,34 @@ type FactoryDefinition<TAttributes extends FactoryAttributes> = (sequence: numbe
|
|
|
11
11
|
type FactoryState<TAttributes extends FactoryAttributes> = (attributes: TAttributes, sequence: number) => TAttributes;
|
|
12
12
|
//#endregion
|
|
13
13
|
//#region src/types/migrations.d.ts
|
|
14
|
-
type SchemaColumnType = 'id' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
|
|
14
|
+
type SchemaColumnType = 'id' | 'uuid' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
|
|
15
15
|
interface SchemaColumn {
|
|
16
16
|
name: string;
|
|
17
17
|
type: SchemaColumnType;
|
|
18
|
+
map?: string;
|
|
18
19
|
nullable?: boolean;
|
|
19
20
|
unique?: boolean;
|
|
20
21
|
primary?: boolean;
|
|
22
|
+
autoIncrement?: boolean;
|
|
23
|
+
after?: string;
|
|
21
24
|
default?: unknown;
|
|
22
25
|
}
|
|
26
|
+
interface SchemaIndex {
|
|
27
|
+
columns: string[];
|
|
28
|
+
name?: string;
|
|
29
|
+
}
|
|
23
30
|
interface SchemaTableCreateOperation {
|
|
24
31
|
type: 'createTable';
|
|
25
32
|
table: string;
|
|
26
33
|
columns: SchemaColumn[];
|
|
34
|
+
indexes: SchemaIndex[];
|
|
27
35
|
}
|
|
28
36
|
interface SchemaTableAlterOperation {
|
|
29
37
|
type: 'alterTable';
|
|
30
38
|
table: string;
|
|
31
39
|
addColumns: SchemaColumn[];
|
|
32
40
|
dropColumns: string[];
|
|
41
|
+
addIndexes: SchemaIndex[];
|
|
33
42
|
}
|
|
34
43
|
interface SchemaTableDropOperation {
|
|
35
44
|
type: 'dropTable';
|
|
@@ -2215,6 +2224,23 @@ declare class SeedCommand extends Command<CliApp> {
|
|
|
2215
2224
|
declare class TableBuilder {
|
|
2216
2225
|
private readonly columns;
|
|
2217
2226
|
private readonly dropColumnNames;
|
|
2227
|
+
private readonly indexes;
|
|
2228
|
+
private latestColumnName;
|
|
2229
|
+
/**
|
|
2230
|
+
* Defines a primary key column in the table.
|
|
2231
|
+
*
|
|
2232
|
+
* @param columnNameOrOptions
|
|
2233
|
+
* @param options
|
|
2234
|
+
* @returns
|
|
2235
|
+
*/
|
|
2236
|
+
primary(columnNameOrOptions?: string | {
|
|
2237
|
+
columnName?: string;
|
|
2238
|
+
autoIncrement?: boolean;
|
|
2239
|
+
default?: unknown;
|
|
2240
|
+
}, options?: {
|
|
2241
|
+
autoIncrement?: boolean;
|
|
2242
|
+
default?: unknown;
|
|
2243
|
+
}): this;
|
|
2218
2244
|
/**
|
|
2219
2245
|
* Defines an auto-incrementing primary key column.
|
|
2220
2246
|
*
|
|
@@ -2222,7 +2248,15 @@ declare class TableBuilder {
|
|
|
2222
2248
|
* @default 'id'
|
|
2223
2249
|
* @returns The current TableBuilder instance for chaining.
|
|
2224
2250
|
*/
|
|
2225
|
-
id(name?: string): this;
|
|
2251
|
+
id(name?: string, type?: Exclude<SchemaColumnType, 'boolean' | 'timestamp' | 'date' | 'json'>): this;
|
|
2252
|
+
/**
|
|
2253
|
+
* Defines a UUID column in the table.
|
|
2254
|
+
*
|
|
2255
|
+
* @param name The name of the UUID column.
|
|
2256
|
+
* @param options Additional options for the UUID column.
|
|
2257
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2258
|
+
*/
|
|
2259
|
+
uuid(name: string, options?: Partial<SchemaColumn>): this;
|
|
2226
2260
|
/**
|
|
2227
2261
|
* Defines a string column in the table.
|
|
2228
2262
|
*
|
|
@@ -2329,6 +2363,37 @@ declare class TableBuilder {
|
|
|
2329
2363
|
* @returns
|
|
2330
2364
|
*/
|
|
2331
2365
|
dropColumn(name: string): this;
|
|
2366
|
+
/**
|
|
2367
|
+
* Marks a column as nullable.
|
|
2368
|
+
*
|
|
2369
|
+
* @param columnName Optional explicit column name. When omitted, applies to the latest defined column.
|
|
2370
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2371
|
+
*/
|
|
2372
|
+
nullable(columnName?: string): this;
|
|
2373
|
+
/**
|
|
2374
|
+
* Sets the column position to appear after another column when possible.
|
|
2375
|
+
*
|
|
2376
|
+
* @param referenceColumn The column that the target column should be placed after.
|
|
2377
|
+
* @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
|
|
2378
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2379
|
+
*/
|
|
2380
|
+
after(referenceColumn: string, columnName?: string): this;
|
|
2381
|
+
/**
|
|
2382
|
+
* Maps the column to a custom database column name.
|
|
2383
|
+
*
|
|
2384
|
+
* @param name The custom database column name.
|
|
2385
|
+
* @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
|
|
2386
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2387
|
+
*/
|
|
2388
|
+
map(name: string, columnName?: string): this;
|
|
2389
|
+
/**
|
|
2390
|
+
* Defines an index on one or more columns.
|
|
2391
|
+
*
|
|
2392
|
+
* @param columns Optional target columns. When omitted, applies to the latest defined column.
|
|
2393
|
+
* @param name Optional index name.
|
|
2394
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2395
|
+
*/
|
|
2396
|
+
index(columns?: string | string[], name?: string): this;
|
|
2332
2397
|
/**
|
|
2333
2398
|
* Returns a deep copy of the defined columns for the table.
|
|
2334
2399
|
*
|
|
@@ -2341,6 +2406,12 @@ declare class TableBuilder {
|
|
|
2341
2406
|
* @returns
|
|
2342
2407
|
*/
|
|
2343
2408
|
getDropColumns(): string[];
|
|
2409
|
+
/**
|
|
2410
|
+
* Returns a deep copy of the defined indexes for the table.
|
|
2411
|
+
*
|
|
2412
|
+
* @returns
|
|
2413
|
+
*/
|
|
2414
|
+
getIndexes(): SchemaIndex[];
|
|
2344
2415
|
/**
|
|
2345
2416
|
* Defines a column in the table with the given name.
|
|
2346
2417
|
*
|
|
@@ -2350,6 +2421,13 @@ declare class TableBuilder {
|
|
|
2350
2421
|
* @returns
|
|
2351
2422
|
*/
|
|
2352
2423
|
private column;
|
|
2424
|
+
/**
|
|
2425
|
+
* Resolve a target column by name or fallback to the latest defined column.
|
|
2426
|
+
*
|
|
2427
|
+
* @param columnName
|
|
2428
|
+
* @returns
|
|
2429
|
+
*/
|
|
2430
|
+
private resolveColumn;
|
|
2353
2431
|
}
|
|
2354
2432
|
//#endregion
|
|
2355
2433
|
//#region src/database/SchemaBuilder.d.ts
|
|
@@ -2515,6 +2593,13 @@ declare const formatDefaultValue: (value: unknown) => string | undefined;
|
|
|
2515
2593
|
* @returns
|
|
2516
2594
|
*/
|
|
2517
2595
|
declare const buildFieldLine: (column: SchemaColumn) => string;
|
|
2596
|
+
/**
|
|
2597
|
+
* Build a Prisma model-level @@index definition line.
|
|
2598
|
+
*
|
|
2599
|
+
* @param index
|
|
2600
|
+
* @returns
|
|
2601
|
+
*/
|
|
2602
|
+
declare const buildIndexLine: (index: SchemaIndex) => string;
|
|
2518
2603
|
/**
|
|
2519
2604
|
* Build a Prisma model block string based on a SchemaTableCreateOperation, including
|
|
2520
2605
|
* all fields and any necessary mapping.
|
|
@@ -2773,4 +2858,4 @@ declare class URLDriver {
|
|
|
2773
2858
|
url(page: number): string;
|
|
2774
2859
|
}
|
|
2775
2860
|
//#endregion
|
|
2776
|
-
export { ArkormCollection, ArkormException, CliApp, InitCommand, InlineFactory, LengthAwarePaginator, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, Migration, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, SchemaBuilder, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildMigrationSource, buildModelBlock, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, ensureArkormConfigLoading, escapeRegex, findModelBlock, formatDefaultValue, generateMigrationFile, getDefaultStubsPath, getMigrationPlan, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, loadArkormConfig, pad, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolvePrismaType, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName };
|
|
2861
|
+
export { ArkormCollection, ArkormException, CliApp, InitCommand, InlineFactory, LengthAwarePaginator, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, Migration, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, SchemaBuilder, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildIndexLine, buildMigrationSource, buildModelBlock, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, ensureArkormConfigLoading, escapeRegex, findModelBlock, formatDefaultValue, generateMigrationFile, getDefaultStubsPath, getMigrationPlan, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, loadArkormConfig, pad, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolvePrismaType, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName };
|
package/dist/index.d.mts
CHANGED
|
@@ -11,25 +11,34 @@ type FactoryDefinition<TAttributes extends FactoryAttributes> = (sequence: numbe
|
|
|
11
11
|
type FactoryState<TAttributes extends FactoryAttributes> = (attributes: TAttributes, sequence: number) => TAttributes;
|
|
12
12
|
//#endregion
|
|
13
13
|
//#region src/types/migrations.d.ts
|
|
14
|
-
type SchemaColumnType = 'id' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
|
|
14
|
+
type SchemaColumnType = 'id' | 'uuid' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
|
|
15
15
|
interface SchemaColumn {
|
|
16
16
|
name: string;
|
|
17
17
|
type: SchemaColumnType;
|
|
18
|
+
map?: string;
|
|
18
19
|
nullable?: boolean;
|
|
19
20
|
unique?: boolean;
|
|
20
21
|
primary?: boolean;
|
|
22
|
+
autoIncrement?: boolean;
|
|
23
|
+
after?: string;
|
|
21
24
|
default?: unknown;
|
|
22
25
|
}
|
|
26
|
+
interface SchemaIndex {
|
|
27
|
+
columns: string[];
|
|
28
|
+
name?: string;
|
|
29
|
+
}
|
|
23
30
|
interface SchemaTableCreateOperation {
|
|
24
31
|
type: 'createTable';
|
|
25
32
|
table: string;
|
|
26
33
|
columns: SchemaColumn[];
|
|
34
|
+
indexes: SchemaIndex[];
|
|
27
35
|
}
|
|
28
36
|
interface SchemaTableAlterOperation {
|
|
29
37
|
type: 'alterTable';
|
|
30
38
|
table: string;
|
|
31
39
|
addColumns: SchemaColumn[];
|
|
32
40
|
dropColumns: string[];
|
|
41
|
+
addIndexes: SchemaIndex[];
|
|
33
42
|
}
|
|
34
43
|
interface SchemaTableDropOperation {
|
|
35
44
|
type: 'dropTable';
|
|
@@ -2215,6 +2224,23 @@ declare class SeedCommand extends Command<CliApp> {
|
|
|
2215
2224
|
declare class TableBuilder {
|
|
2216
2225
|
private readonly columns;
|
|
2217
2226
|
private readonly dropColumnNames;
|
|
2227
|
+
private readonly indexes;
|
|
2228
|
+
private latestColumnName;
|
|
2229
|
+
/**
|
|
2230
|
+
* Defines a primary key column in the table.
|
|
2231
|
+
*
|
|
2232
|
+
* @param columnNameOrOptions
|
|
2233
|
+
* @param options
|
|
2234
|
+
* @returns
|
|
2235
|
+
*/
|
|
2236
|
+
primary(columnNameOrOptions?: string | {
|
|
2237
|
+
columnName?: string;
|
|
2238
|
+
autoIncrement?: boolean;
|
|
2239
|
+
default?: unknown;
|
|
2240
|
+
}, options?: {
|
|
2241
|
+
autoIncrement?: boolean;
|
|
2242
|
+
default?: unknown;
|
|
2243
|
+
}): this;
|
|
2218
2244
|
/**
|
|
2219
2245
|
* Defines an auto-incrementing primary key column.
|
|
2220
2246
|
*
|
|
@@ -2222,7 +2248,15 @@ declare class TableBuilder {
|
|
|
2222
2248
|
* @default 'id'
|
|
2223
2249
|
* @returns The current TableBuilder instance for chaining.
|
|
2224
2250
|
*/
|
|
2225
|
-
id(name?: string): this;
|
|
2251
|
+
id(name?: string, type?: Exclude<SchemaColumnType, 'boolean' | 'timestamp' | 'date' | 'json'>): this;
|
|
2252
|
+
/**
|
|
2253
|
+
* Defines a UUID column in the table.
|
|
2254
|
+
*
|
|
2255
|
+
* @param name The name of the UUID column.
|
|
2256
|
+
* @param options Additional options for the UUID column.
|
|
2257
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2258
|
+
*/
|
|
2259
|
+
uuid(name: string, options?: Partial<SchemaColumn>): this;
|
|
2226
2260
|
/**
|
|
2227
2261
|
* Defines a string column in the table.
|
|
2228
2262
|
*
|
|
@@ -2329,6 +2363,37 @@ declare class TableBuilder {
|
|
|
2329
2363
|
* @returns
|
|
2330
2364
|
*/
|
|
2331
2365
|
dropColumn(name: string): this;
|
|
2366
|
+
/**
|
|
2367
|
+
* Marks a column as nullable.
|
|
2368
|
+
*
|
|
2369
|
+
* @param columnName Optional explicit column name. When omitted, applies to the latest defined column.
|
|
2370
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2371
|
+
*/
|
|
2372
|
+
nullable(columnName?: string): this;
|
|
2373
|
+
/**
|
|
2374
|
+
* Sets the column position to appear after another column when possible.
|
|
2375
|
+
*
|
|
2376
|
+
* @param referenceColumn The column that the target column should be placed after.
|
|
2377
|
+
* @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
|
|
2378
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2379
|
+
*/
|
|
2380
|
+
after(referenceColumn: string, columnName?: string): this;
|
|
2381
|
+
/**
|
|
2382
|
+
* Maps the column to a custom database column name.
|
|
2383
|
+
*
|
|
2384
|
+
* @param name The custom database column name.
|
|
2385
|
+
* @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
|
|
2386
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2387
|
+
*/
|
|
2388
|
+
map(name: string, columnName?: string): this;
|
|
2389
|
+
/**
|
|
2390
|
+
* Defines an index on one or more columns.
|
|
2391
|
+
*
|
|
2392
|
+
* @param columns Optional target columns. When omitted, applies to the latest defined column.
|
|
2393
|
+
* @param name Optional index name.
|
|
2394
|
+
* @returns The current TableBuilder instance for chaining.
|
|
2395
|
+
*/
|
|
2396
|
+
index(columns?: string | string[], name?: string): this;
|
|
2332
2397
|
/**
|
|
2333
2398
|
* Returns a deep copy of the defined columns for the table.
|
|
2334
2399
|
*
|
|
@@ -2341,6 +2406,12 @@ declare class TableBuilder {
|
|
|
2341
2406
|
* @returns
|
|
2342
2407
|
*/
|
|
2343
2408
|
getDropColumns(): string[];
|
|
2409
|
+
/**
|
|
2410
|
+
* Returns a deep copy of the defined indexes for the table.
|
|
2411
|
+
*
|
|
2412
|
+
* @returns
|
|
2413
|
+
*/
|
|
2414
|
+
getIndexes(): SchemaIndex[];
|
|
2344
2415
|
/**
|
|
2345
2416
|
* Defines a column in the table with the given name.
|
|
2346
2417
|
*
|
|
@@ -2350,6 +2421,13 @@ declare class TableBuilder {
|
|
|
2350
2421
|
* @returns
|
|
2351
2422
|
*/
|
|
2352
2423
|
private column;
|
|
2424
|
+
/**
|
|
2425
|
+
* Resolve a target column by name or fallback to the latest defined column.
|
|
2426
|
+
*
|
|
2427
|
+
* @param columnName
|
|
2428
|
+
* @returns
|
|
2429
|
+
*/
|
|
2430
|
+
private resolveColumn;
|
|
2353
2431
|
}
|
|
2354
2432
|
//#endregion
|
|
2355
2433
|
//#region src/database/SchemaBuilder.d.ts
|
|
@@ -2515,6 +2593,13 @@ declare const formatDefaultValue: (value: unknown) => string | undefined;
|
|
|
2515
2593
|
* @returns
|
|
2516
2594
|
*/
|
|
2517
2595
|
declare const buildFieldLine: (column: SchemaColumn) => string;
|
|
2596
|
+
/**
|
|
2597
|
+
* Build a Prisma model-level @@index definition line.
|
|
2598
|
+
*
|
|
2599
|
+
* @param index
|
|
2600
|
+
* @returns
|
|
2601
|
+
*/
|
|
2602
|
+
declare const buildIndexLine: (index: SchemaIndex) => string;
|
|
2518
2603
|
/**
|
|
2519
2604
|
* Build a Prisma model block string based on a SchemaTableCreateOperation, including
|
|
2520
2605
|
* all fields and any necessary mapping.
|
|
@@ -2773,4 +2858,4 @@ declare class URLDriver {
|
|
|
2773
2858
|
url(page: number): string;
|
|
2774
2859
|
}
|
|
2775
2860
|
//#endregion
|
|
2776
|
-
export { ArkormCollection, ArkormException, CliApp, InitCommand, InlineFactory, LengthAwarePaginator, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, Migration, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, SchemaBuilder, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildMigrationSource, buildModelBlock, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, ensureArkormConfigLoading, escapeRegex, findModelBlock, formatDefaultValue, generateMigrationFile, getDefaultStubsPath, getMigrationPlan, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, loadArkormConfig, pad, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolvePrismaType, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName };
|
|
2861
|
+
export { ArkormCollection, ArkormException, CliApp, InitCommand, InlineFactory, LengthAwarePaginator, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, Migration, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, SchemaBuilder, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildIndexLine, buildMigrationSource, buildModelBlock, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, ensureArkormConfigLoading, escapeRegex, findModelBlock, formatDefaultValue, generateMigrationFile, getDefaultStubsPath, getMigrationPlan, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, loadArkormConfig, pad, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolvePrismaType, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName };
|
package/dist/index.mjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdirSync as i,rmSync as a,writeFileSync as o}from"fs";import s,{dirname as c,extname as l,join as u,relative as d}from"path";import{createRequire as f}from"module";import{existsSync as p,mkdirSync as m,readFileSync as h,readdirSync as g,writeFileSync as _}from"node:fs";import{join as v,resolve as y}from"node:path";import{
|
|
2
|
-
`)}
|
|
3
|
-
`);t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${D(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}})
|
|
4
|
-
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},
|
|
1
|
+
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdirSync as i,rmSync as a,writeFileSync as o}from"fs";import s,{dirname as c,extname as l,join as u,relative as d}from"path";import{createRequire as f}from"module";import{existsSync as p,mkdirSync as m,readFileSync as h,readdirSync as g,writeFileSync as _}from"node:fs";import{join as v,resolve as y}from"node:path";import{spawnSync as ee}from"node:child_process";import{str as b}from"@h3ravel/support";import{fileURLToPath as te,pathToFileURL as ne}from"url";import{Logger as re}from"@h3ravel/shared";import{Command as x}from"@h3ravel/musket";import{pathToFileURL as ie}from"node:url";import{Collection as ae}from"@h3ravel/collect.js";const oe={string:{get:e=>e==null?e:String(e),set:e=>e==null?e:String(e)},number:{get:e=>e==null?e:Number(e),set:e=>e==null?e:Number(e)},boolean:{get:e=>e==null?e:!!e,set:e=>e==null?e:!!e},date:{get:e=>e==null||e instanceof Date?e:new Date(String(e)),set:e=>e==null||e instanceof Date?e:new Date(String(e))},json:{get:e=>{if(e==null||typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},set:e=>e==null||typeof e==`string`?e:JSON.stringify(e)},array:{get:e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{return[e]}return e==null?e:[e]},set:e=>e==null||Array.isArray(e)?e:[e]}};function S(e){return typeof e==`string`?oe[e]:e}var C=class extends Error{constructor(e){super(e),this.name=`ArkormException`}},w=class{},T=class{columns=[];dropColumnNames=[];indexes=[];latestColumnName;primary(e,t){let n=typeof e==`string`?{columnName:e,...t??{}}:e??{},r=this.resolveColumn(n.columnName);return r.primary=!0,typeof n.autoIncrement==`boolean`&&(r.autoIncrement=n.autoIncrement),Object.prototype.hasOwnProperty.call(n,`default`)&&(r.default=n.default),this}id(e=`id`,t=`id`){return this.column(e,t,{primary:!0})}uuid(e,t={}){return this.column(e,`uuid`,t)}string(e,t={}){return this.column(e,`string`,t)}text(e,t={}){return this.column(e,`text`,t)}integer(e,t={}){return this.column(e,`integer`,t)}bigInteger(e,t={}){return this.column(e,`bigInteger`,t)}float(e,t={}){return this.column(e,`float`,t)}boolean(e,t={}){return this.column(e,`boolean`,t)}json(e,t={}){return this.column(e,`json`,t)}date(e,t={}){return this.column(e,`date`,t)}morphs(e,t=!1){return this.string(`${e}Type`,{nullable:t}),this.integer(`${e}Id`,{nullable:t}),this}nullableMorphs(e){return this.morphs(e,!0)}timestamp(e,t={}){return this.column(e,`timestamp`,t)}timestamps(){return this.timestamp(`createdAt`,{nullable:!1}),this.timestamp(`updatedAt`,{nullable:!1}),this}softDeletes(e=`deletedAt`){return this.timestamp(e,{nullable:!0}),this}dropColumn(e){return this.dropColumnNames.push(e),this}nullable(e){let t=this.resolveColumn(e);return t.nullable=!0,this}after(e,t){let n=this.resolveColumn(t);return n.after=e,this}map(e,t){let n=this.resolveColumn(t);return n.map=e,this}index(e,t){let n=Array.isArray(e)?e:typeof e==`string`?[e]:[this.resolveColumn().name];return this.indexes.push({columns:[...n],name:t}),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}getIndexes(){return this.indexes.map(e=>({...e,columns:[...e.columns]}))}column(e,t,n){return this.columns.push({name:e,type:t,map:n.map,nullable:n.nullable,unique:n.unique,primary:n.primary,autoIncrement:n.autoIncrement,after:n.after,default:n.default}),this.latestColumnName=e,this}resolveColumn(e){let t=e??this.latestColumnName;if(!t)throw Error(`No column available for this operation.`);let n=this.columns.find(e=>e.name===t);if(!n)throw Error(`Column [${t}] was not found in the table definition.`);return n}},se=class{operations=[];createTable(e,t){let n=new T;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns(),indexes:n.getIndexes()}),this}alterTable(e,t){let n=new T;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns(),addIndexes:n.getIndexes()}),this}dropTable(e){return this.operations.push({type:`dropTable`,table:e}),this}getOperations(){return this.operations.map(e=>e.type===`createTable`?{...e,columns:e.columns.map(e=>({...e})),indexes:e.indexes.map(e=>({...e,columns:[...e.columns]}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns],addIndexes:e.addIndexes.map(e=>({...e,columns:[...e.columns]}))}:{...e})}};const ce=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,E=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim(),n=(t.endsWith(`s`)&&t.length>1?t.slice(0,-1):t).split(/\s+/g).filter(Boolean);return n.length===0?`GeneratedModel`:n.map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)},D=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),le=e=>e.type===`id`?`Int`:e.type===`uuid`||e.type===`string`||e.type===`text`?`String`:e.type===`integer`?`Int`:e.type===`bigInteger`?`BigInt`:e.type===`float`?`Float`:e.type===`boolean`?`Boolean`:e.type===`json`?`Json`:`DateTime`,O=e=>{if(e!=null){if(typeof e==`string`)return`@default("${e.replace(/"/g,`\\"`)}")`;if(typeof e==`number`||typeof e==`bigint`)return`@default(${e})`;if(typeof e==`boolean`)return`@default(${e?`true`:`false`})`}},k=e=>{if(e.type===`id`){let t=e.primary===!1?``:` @id`,n=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,r=O(e.default),i=e.autoIncrement??e.primary!==!1,a=r?` ${r}`:i&&t?` @default(autoincrement())`:``;return` ${e.name} Int${t}${a}${n}`}let t=le(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,o=O(e.default)??(e.type===`uuid`&&e.primary?`@default(uuid())`:void 0),s=o?` ${o}`:``;return` ${e.name} ${t}${n}${i}${r}${s}${a}`},A=e=>` @@index([${e.columns.join(`, `)}]${typeof e.name==`string`&&e.name.trim().length>0?`, name: "${e.name.replace(/"/g,`\\"`)}"`:``})`,ue=e=>{let t=E(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(k),i=[...(e.indexes??[]).map(A),...n?[` @@map("${b(e.table).snake()}")`]:[]];return`model ${t} {\n${(i.length>0?[...r,``,...i]:r).join(`
|
|
2
|
+
`)}\n}`},j=(e,t)=>{let n=[...e.matchAll(ce)],r=RegExp(`@@map\\("${D(t)}"\\)`);for(let e of n){let n=e[0],i=e[1],a=e.index??0,o=a+n.length;if(r.test(n)||i.toLowerCase()===t.toLowerCase()||i.toLowerCase()===E(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},M=(e,t)=>{if(j(e,t.table))throw new C(`Prisma model for table [${t.table}] already exists.`);let n=ue(t);return`${e.trimEnd()}\n\n${n}\n`},de=(e,t)=>{let n=j(e,t.table);if(!n)throw new C(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
|
|
3
|
+
`);return t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${D(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}}),t.addColumns.forEach(e=>{let t=k(e),n=RegExp(`^\\s*${D(e.name)}\\s+`);if(i.some(e=>n.test(e)))return;let r=Math.max(1,i.length-1),a=typeof e.after==`string`&&e.after.length>0?i.findIndex(t=>RegExp(`^\\s*${D(e.after)}\\s+`).test(t)):-1,o=a>0?Math.min(a+1,r):r;i.splice(o,0,t)}),(t.addIndexes??[]).forEach(e=>{let t=A(e);if(i.some(e=>e.trim()===t.trim()))return;let n=Math.max(1,i.length-1);i.splice(n,0,t)}),r=i.join(`
|
|
4
|
+
`),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},fe=(e,t)=>{let n=j(e,t.table);if(!n)return e;let r=e.slice(0,n.start).trimEnd(),i=e.slice(n.end).trimStart();return`${r}${r&&i?`
|
|
5
5
|
|
|
6
|
-
`:``}${i}`},
|
|
7
|
-
`).trim();throw new C(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},
|
|
6
|
+
`:``}${i}`},pe=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?M(e,t):t.type===`alterTable`?de(e,t):fe(e,t),e),N=(e,t)=>{let n=ee(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
|
|
7
|
+
`).trim();throw new C(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},me=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim();return t?`${t.split(/\s+/g).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)}Migration`:`GeneratedMigration`},P=e=>String(e).padStart(2,`0`),F=(e=new Date)=>`${e.getFullYear()}${P(e.getMonth()+1)}${P(e.getDate())}${P(e.getHours())}${P(e.getMinutes())}${P(e.getSeconds())}`,he=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,ge=(e,t=`ts`)=>t===`js`?[`import { Migration } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async up (schema) {`,` }`,``,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async down (schema) {`,` }`,`}`,``].join(`
|
|
8
8
|
`):[`import { Migration, SchemaBuilder } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` public async up (schema: SchemaBuilder): Promise<void> {`,` }`,``,` public async down (schema: SchemaBuilder): Promise<void> {`,` }`,`}`,``].join(`
|
|
9
|
-
`),
|
|
9
|
+
`),_e=(e,t={})=>{let n=F(new Date),r=he(e),i=me(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=ge(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new C(`Migration file already exists: ${c}`);_(c,l)}return{fileName:s,filePath:c,className:i,content:l}},ve=async(e,t=`up`)=>{let n=e instanceof w?e:new e,r=new se;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},I=async(e,t={})=>{let n=t.schemaPath??v(process.cwd(),`prisma`,`schema.prisma`);if(!p(n))throw new C(`Prisma schema file not found: ${n}`);let r=h(n,`utf-8`),i=await ve(e,`up`),a=pe(r,i);return(t.write??!0)&&_(n,a),{schema:a,schemaPath:n,operations:i}},ye=async(e,t={})=>{let n=t.cwd??process.cwd(),r=await I(e,{schemaPath:t.schemaPath??v(n,`prisma`,`schema.prisma`),write:t.write}),i=t.runGenerate??!0,a=t.runMigrate??!0,o=t.migrateMode??`dev`;return i&&N([`generate`],n),a&&N(o===`deploy`?[`migrate`,`deploy`]:[`migrate`,`dev`,`--name`,t.migrationName??`arkorm_${F()}`],n),{schemaPath:r.schemaPath,operations:r.operations}},be=()=>{let e=s.dirname(te(import.meta.url));for(;;){let n=s.join(e,`package.json`),r=s.join(e,`stubs`);if(t(n)&&t(r))return r;let i=s.dirname(e);if(i===e)break;e=i}return s.join(process.cwd(),`stubs`)},L={paths:{stubs:be(),seeders:s.join(process.cwd(),`database`,`seeders`),models:s.join(process.cwd(),`src`,`models`),migrations:s.join(process.cwd(),`database`,`migrations`),factories:s.join(process.cwd(),`database`,`factories`),buildOutput:s.join(process.cwd(),`dist`)},outputExt:`ts`},R={...L,paths:{...L.paths??{}}};let z=!1,B,V,H;const xe=e=>{let t=L.paths??{},n=R.paths??{},r=Object.entries(e??{}).reduce((e,[t,n])=>(typeof n==`string`&&n.trim().length>0&&(e[t]=n),e),{});return{...t,...n,...r}},Se=e=>e,U=e=>e?R[e]:R,Ce=(e,t={})=>{let n={...R,prisma:e,paths:xe(t.paths)};t.pagination!==void 0&&(n.pagination=t.pagination),t.outputExt!==void 0&&(n.outputExt=t.outputExt),Object.assign(R,{...n}),V=e,H=n.pagination?.urlDriver},we=()=>{Object.assign(R,{...L,paths:{...L.paths??{}}}),z=!1,B=void 0,V=void 0,H=void 0},Te=e=>{if(!e)return;let t=typeof e==`function`?e():e;if(!(!t||typeof t!=`object`))return t},Ee=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(Ce(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),z=!0)},De=e=>import(`${ne(e).href}?arkorm_runtime=${Date.now()}`),W=()=>{let e=f(import.meta.url),n=[s.join(process.cwd(),`arkormx.config.cjs`)];for(let r of n)if(t(r))try{return Ee(e(r)),!0}catch{continue}return!1},G=async()=>{if(!z){if(B)return await B;W()||(B=(async()=>{let e=[s.join(process.cwd(),`arkormx.config.js`),s.join(process.cwd(),`arkormx.config.ts`)];for(let n of e)if(t(n))try{Ee(await De(n));return}catch{continue}z=!0})(),await B)}},Oe=()=>{z||B||G()},K=()=>be(),ke=()=>(z||W(),Te(V)),q=()=>(z||W(),H),J=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return[`findMany`,`findFirst`,`create`,`update`,`delete`,`count`].every(e=>typeof t[e]==`function`)};G();var Ae=class{command;config={};constructor(){this.config=U()}getConfig=U;ensureDirectory(e){let r=c(e);t(r)||n(r,{recursive:!0})}formatPathForLog(e){let t=d(process.cwd(),e);return t?t.startsWith(`..`)?e:t:`.`}splitLogger(e,t){return t=t.includes(process.cwd())?this.formatPathForLog(t):t,re.twoColumnDetail(e+` `,` `+t,!1).join(``)}hasTypeScriptInstalled(){try{return f(import.meta.url).resolve(`typescript`,{paths:[process.cwd()]}),!0}catch{return!1}}resolveOutputExt(){let e=this.getConfig(`outputExt`)===`js`?`js`:`ts`;return e===`ts`&&!this.hasTypeScriptInstalled()?`js`:e}stripKnownSourceExtension(e){return e.replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}resolveRuntimeDirectoryPath(e){if(t(e))return e;let{buildOutput:n}=this.getConfig(`paths`)||{};if(typeof n!=`string`||n.trim().length===0)return e;let r=d(process.cwd(),e);if(!r||r.startsWith(`..`))return e;let i=u(n,r);return t(i)?i:e}resolveRuntimeScriptPath(e){let n=l(e).toLowerCase(),r=n===`.ts`||n===`.mts`||n===`.cts`,i=[];if(r){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}let{buildOutput:a}=this.getConfig(`paths`)??{};if(typeof a==`string`&&a.trim().length>0){let t=d(process.cwd(),e);if(t&&!t.startsWith(`..`)){let e=u(a,t),n=l(e).toLowerCase();if(n===`.ts`||n===`.mts`||n===`.cts`){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}else i.push(e)}}return i.find(e=>t(e))||e}generateFile(e,n,i,s){t(n)&&!s?.force?(this.command.error(`Error: ${this.formatPathForLog(n)} already exists.`),process.exit(1)):t(n)&&s?.force&&a(n);let c=r(e,`utf-8`);for(let[e,t]of Object.entries(i))c=c.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(n),o(n,c),n}resolveConfigPath(e,t){let{[e]:n}=this.getConfig(`paths`)??{};return typeof n==`string`&&n.trim().length>0?n:t}resolveStubPath(e){return u(this.resolveConfigPath(`stubs`,K()),e)}makeFactory(e,t={}){let n=b(e.replace(/Factory$/,``)).pascal(),r=`${n}Factory`,i=t.modelName?b(t.modelName).pascal():n,a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${r}.${a}`),s=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${i}.${a}`),l=t.modelImportPath??`./${this.stripKnownSourceExtension(d(c(o),s).replace(/\\/g,`/`))}${a===`js`?`.js`:``}`,f=this.resolveStubPath(a===`js`?`factory.js.stub`:`factory.stub`);return{name:r,path:this.generateFile(f,o,{FactoryName:r,ModelName:i.toString(),ModelImportPath:l.startsWith(`.`)?l:`./${l}`},t)}}makeSeeder(e,t={}){let n=`${b(e.replace(/Seeder$/,``)).pascal()}Seeder`,r=this.resolveOutputExt(),i=u(this.resolveConfigPath(`seeders`,u(process.cwd(),`database`,`seeders`)),`${n}.${r}`),a=this.resolveStubPath(r===`js`?`seeder.js.stub`:`seeder.stub`);return{name:n,path:this.generateFile(a,i,{SeederName:n},t)}}makeMigration(e){let t=_e(e,{directory:this.resolveConfigPath(`migrations`,u(process.cwd(),`database`,`migrations`)),extension:this.resolveOutputExt()});return{name:t.className,path:t.filePath}}makeModel(e,t={}){let n=b(e.replace(/Model$/,``)).pascal().toString(),r=`${n}`,i=b(n).camel().plural().toString(),a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${r}.${a}`),s=t.all||t.factory,l=t.all||t.seeder,f=t.all||t.migration,p=`${n}Factory`,m=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${p}.${a}`),h=`./${d(c(o),m).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`,g=this.resolveStubPath(a===`js`?`model.js.stub`:`model.stub`),_=this.generateFile(g,o,{ModelName:r,DelegateName:i,FactoryImport:s?`import { ${p} } from '${h}'\n`:``,FactoryLink:s?a===`js`?`\n static factoryClass = ${p}`:`\n protected static override factoryClass = ${p}`:``},t),v=this.ensurePrismaModelEntry(r,i),y={model:{name:r,path:_},prisma:v,factory:void 0,seeder:void 0,migration:void 0};return s&&(y.factory=this.makeFactory(n,{force:t.force,modelName:r,modelImportPath:`./${d(c(m),o).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`})),l&&(y.seeder=this.makeSeeder(n,{force:t.force})),f&&(y.migration=this.makeMigration(`create ${i} table`)),y}ensurePrismaModelEntry(e,n){let i=u(process.cwd(),`prisma`,`schema.prisma`);if(!t(i))return{path:i,updated:!1};let a=r(i,`utf-8`),s=j(a,n),c=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(a);return s||c?{path:i,updated:!1}:(o(i,M(a,{type:`createTable`,table:n,columns:[{name:`id`,type:`id`,primary:!0}]})),{path:i,updated:!0})}prismaTypeToTs(e){return e===`Int`||e===`Float`||e===`Decimal`?`number`:e===`BigInt`?`bigint`:e===`String`?`string`:e===`Boolean`?`boolean`:e===`DateTime`?`Date`:e===`Json`?`Record<string, unknown>`:e===`Bytes`?`Buffer`:`unknown`}parsePrismaModels(e){let t=[],n=/model\s+(\w+)\s*\{([\s\S]*?)\n\}/g,r=new Set([`Int`,`Float`,`Decimal`,`BigInt`,`String`,`Boolean`,`DateTime`,`Json`,`Bytes`]);for(let i of e.matchAll(n)){let e=i[1],n=i[2],a=n.match(/@@map\("([^"]+)"\)/)?.[1]??`${e.charAt(0).toLowerCase()}${e.slice(1)}s`,o=[];n.split(`
|
|
10
10
|
`).forEach(e=>{let t=e.trim();if(!t||t.startsWith(`@@`)||t.startsWith(`//`))return;let n=t.match(/^(\w+)\s+([A-Za-z]+)(\?)?\b/);if(!n)return;let i=n[2];r.has(i)&&o.push({name:n[1],type:this.prismaTypeToTs(i),optional:!!n[3]})}),t.push({name:e,table:a,fields:o})}return t}syncModelDeclarations(e,t){let n=e.split(`
|
|
11
11
|
`),r=n.findIndex(e=>/export\s+class\s+\w+\s+extends\s+Model<.+>\s*\{/.test(e));if(r<0)return{content:e,updated:!1};let i=-1,a=0;for(let e=r;e<n.length;e+=1){let t=n[e];if(a+=(t.match(/\{/g)||[]).length,a-=(t.match(/\}/g)||[]).length,a===0){i=e;break}}if(i<0)return{content:e,updated:!1};let o=n.slice(r+1,i).filter(e=>!/^\s*declare\s+\w+\??:\s*[^\n]+$/.test(e)),s=[...t.map(e=>` ${e}`),...o],c=[...n.slice(0,r+1),...s,...n.slice(i)].join(`
|
|
12
12
|
`);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let n=e.schemaPath??u(process.cwd(),`prisma`,`schema.prisma`),a=e.modelsDir??this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`));if(!t(n))throw Error(`Prisma schema file not found: ${n}`);if(!t(a))throw Error(`Models directory not found: ${a}`);let s=r(n,`utf-8`),c=this.parsePrismaModels(s),l=i(a).filter(e=>e.endsWith(`.ts`)),d=[],f=[];return l.forEach(e=>{let t=u(a,e),n=r(t,`utf-8`),i=n.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!i){f.push(t);return}let s=i[1],l=i[2],p=c.find(e=>e.table===l)??c.find(e=>e.name===s);if(!p||p.fields.length===0){f.push(t);return}let m=p.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),h=this.syncModelDeclarations(n,m);if(!h.updated){f.push(t);return}o(t,h.content),d.push(t)}),{schemaPath:n,modelsDir:a,total:l.length,updated:d,skipped:f}}},je=class extends x{signature=`init
|
|
13
13
|
{--force : Force overwrite if config file already exists (existing file will be backed up) }
|
|
14
|
-
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let n=v(process.cwd(),`arkormx.config.js`),{stubs:i}=
|
|
14
|
+
`;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let n=v(process.cwd(),`arkormx.config.js`),{stubs:i}=U(`paths`)??{},a=typeof i==`string`&&i.trim().length>0?i:K(),s=v(a,`arkormx.config.stub`),c=v(a,`arkorm.config.stub`),l=t(s)?s:c;t(n)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(n),t(n)&&this.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),t(l)||(this.error(`Error: Missing config stub at ${s} (or ${c})`),process.exit(1)),o(n,r(l,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},Me=class extends x{signature=`make:factory
|
|
15
15
|
{name : Name of the factory to create}
|
|
16
16
|
{--f|force : Overwrite existing file}
|
|
17
17
|
`;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},Ne=class extends x{signature=`make:migration
|
|
@@ -34,7 +34,7 @@ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdi
|
|
|
34
34
|
{--skip-migrate : Skip prisma migrate command}
|
|
35
35
|
{--schema= : Explicit prisma schema path}
|
|
36
36
|
{--migration-name= : Name for prisma migrate dev}
|
|
37
|
-
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??v(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?y(String(this.option(`schema`))):v(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await
|
|
37
|
+
`;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??v(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?y(String(this.option(`schema`))):v(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await I(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||N([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?N([`migrate`,`deploy`],process.cwd()):N([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${ie(y(e)).href}?arkorm_migrate=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof w:!1)}},Le=class extends x{signature=`models:sync
|
|
38
38
|
{--schema= : Path to prisma schema file}
|
|
39
39
|
{--models= : Path to models directory}
|
|
40
40
|
`;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?y(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?y(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},Re=class e{async call(...t){await e.runSeeders(...t)}static toSeederInstance(t){return t instanceof e?t:new t}static async runSeeders(...e){let t=e.reduce((e,t)=>Array.isArray(t)?[...e,...t]:(e.push(t),e),[]);for(let e of t)await this.toSeederInstance(e).run()}},ze=class extends x{signature=`seed
|
|
@@ -47,4 +47,4 @@ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdi
|
|
|
47
47
|
███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
|
|
48
48
|
███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
|
|
49
49
|
███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
|
|
50
|
-
`;var J=class extends ae{},Be=class{amount=1;sequence=0;states=[];count(e){return this.amount=Math.max(1,Math.floor(e)),this}state(e){return this.states.push(e),this}make(e={}){let t=this.buildAttributes(e);return new this.model(t)}makeMany(e=this.amount,t={}){let n=Math.max(1,Math.floor(e));return Array.from({length:n},()=>this.make(t))}async create(e={}){let t=this.make(e);if(typeof t.save!=`function`)throw Error(`Factory model does not support save().`);return await t.save()}async createMany(e=this.amount,t={}){let n=this.makeMany(e,t);return await Promise.all(n.map(async e=>{if(typeof e.save!=`function`)throw Error(`Factory model does not support save().`);return await e.save()}))}buildAttributes(e){let t=this.sequence;this.sequence+=1;let n=this.definition(t);for(let e of this.states)n=e(n,t);return{...n,...e}}},Ve=class extends Be{model;constructor(e,t){super(),this.resolver=t,this.model=e}definition(e){return this.resolver(e)}};const He=(e,t)=>new Ve(e,t);var Y=class extends C{constructor(e=`No query results for the given model.`){super(e),this.name=`ModelNotFoundException`}};function Ue(e){return Object.entries(e).reduce((e,[t,n])=>(q(n)&&(e[t]=n),e),{})}function We(e){return Ue(e)}function Ge(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}s`}var X=class{constraint=null;constrain(e){if(!this.constraint)return this.constraint=e,this;let t=this.constraint;return this.constraint=n=>{let r=t(n)??n;return e(r)??r},this}where(e){return this.constrain(t=>t.where(e))}whereKey(e,t){return this.constrain(n=>n.whereKey(e,t))}whereIn(e,t){return this.constrain(n=>n.whereIn(e,t))}orderBy(e){return this.constrain(t=>t.orderBy(e))}include(e){return this.constrain(t=>t.include(e))}with(e){return this.constrain(t=>t.with(e))}select(e){return this.constrain(t=>t.select(e))}skip(e){return this.constrain(t=>t.skip(e))}take(e){return this.constrain(t=>t.take(e))}withTrashed(){return this.constrain(e=>e.withTrashed())}onlyTrashed(){return this.constrain(e=>e.onlyTrashed())}withoutTrashed(){return this.constrain(e=>e.withoutTrashed())}scope(e,...t){return this.constrain(n=>n.scope(e,...t))}applyConstraint(e){return this.constraint?this.constraint(e)??e:e}async get(){return this.getResults()}async first(){let e=await this.getResults();return e instanceof J?e.all()[0]??null:e}},Ke=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.foreignPivotKey]:e}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:t}})).get()}},qe=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.ownerKey=r}async getResults(){let e=this.parent.getAttribute(this.foreignKey);return this.applyConstraint(this.related.query().where({[this.ownerKey]:e})).first()}},Je=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).get()}},Ye=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.firstKey]:e}})).map(e=>e[this.secondLocalKey]);return this.applyConstraint(this.related.query().where({[this.secondKey]:{in:t}})).get()}},Xe=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).first()}},Ze=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=await this.related.getDelegate(this.throughDelegate).findFirst({where:{[this.firstKey]:e}});return t?this.applyConstraint(this.related.query().where({[this.secondKey]:t[this.secondLocalKey]})).first():null}},Qe=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).get()}},$e=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).first()}},et=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.morphName=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=this.parent.constructor.name,n=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:n}})).get()}},Z=class e{static DEFAULT_PAGE_NAME=`page`;path;query;fragment;pageName;constructor(t={}){this.path=t.path??`/`,this.query=t.query??{},this.fragment=t.fragment??``,this.pageName=t.pageName??e.DEFAULT_PAGE_NAME}getPageName(){return this.pageName}url(e){let t=Math.max(1,e),[n,r=``]=this.path.split(`?`),i=new URLSearchParams(r);Object.entries(this.query).forEach(([e,t])=>{if(t==null){i.delete(e);return}i.set(e,String(t))}),i.set(this.pageName,String(t));let a=i.toString(),o=this.fragment.replace(/^#/,``);return!a&&!o?n:o?a?`${n}?${a}#${o}`:`${n}#${o}`:`${n}?${a}`}},Q=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=Math.max(1,Math.ceil(t/n)),o=t===0?null:(r-1)*n+1,s=t===0?null:Math.min(r*n,t);this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={total:t,perPage:n,currentPage:r,lastPage:a,from:o,to:s}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.currentPage>=this.meta.lastPage?null:this.url(this.meta.currentPage+1)}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}firstPageUrl(){return this.url(1)}lastPageUrl(){return this.url(this.meta.lastPage)}toJSON(){return{data:this.data,meta:this.meta,links:{first:this.firstPageUrl(),last:this.lastPageUrl(),prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},$=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=e.all().length,o=a===0?null:(n-1)*t+1,s=a===0?null:(o??1)+a-1;this.data=e;let c=K();this.urlDriver=c?c(i):new Z(i),this.meta={perPage:t,currentPage:n,from:o,to:s,hasMorePages:r}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.hasMorePages?this.url(this.meta.currentPage+1):null}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}toJSON(){return{data:this.data,meta:this.meta,links:{prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},tt=class e{args={};eagerLoads={};includeTrashed=!1;onlyTrashedRecords=!1;randomOrderEnabled=!1;relationFilters=[];relationAggregates=[];constructor(e,t){this.delegate=e,this.model=t}where(e){return this.addLogicalWhere(`AND`,e)}orWhere(e){return this.addLogicalWhere(`OR`,e)}whereNot(e){return this.where({NOT:e})}orWhereNot(e){return this.orWhere({NOT:e})}whereNull(e){return this.where({[e]:null})}whereNotNull(e){return this.where({[e]:{not:null}})}whereBetween(e,t){let[n,r]=t;return this.where({[e]:{gte:n,lte:r}})}whereDate(e,t){let n=this.coerceDate(t),r=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),this.where({[e]:{gte:r,lt:i}})}whereMonth(e,t,n=new Date().getUTCFullYear()){let r=Math.min(12,Math.max(1,t)),i=new Date(Date.UTC(n,r-1,1)),a=new Date(Date.UTC(n,r,1));return this.where({[e]:{gte:i,lt:a}})}whereYear(e,t){let n=new Date(Date.UTC(t,0,1)),r=new Date(Date.UTC(t+1,0,1));return this.where({[e]:{gte:n,lt:r}})}whereKeyNot(e,t){return this.where({[e]:{not:t}})}orWhereIn(e,t){return this.orWhere({[e]:{in:t}})}whereNotIn(e,t){return this.where({[e]:{notIn:t}})}orWhereNotIn(e,t){return this.orWhere({[e]:{notIn:t}})}async firstWhere(e,t,n){let r=n!==void 0,i=r?t:`=`,a=r?n:t;return this.clone().where(this.buildComparisonWhere(e,i,a)).first()}addLogicalWhere(e,t){return this.args.where?(this.args.where={[e]:[this.args.where,t]},this):(this.args.where=t,this)}buildComparisonWhere(e,t,n){return t===`=`?{[e]:n}:t===`!=`?{[e]:{not:n}}:t===`>`?{[e]:{gt:n}}:t===`>=`?{[e]:{gte:n}}:t===`<`?{[e]:{lt:n}}:{[e]:{lte:n}}}coerceDate(e){let t=e instanceof Date?new Date(e.getTime()):new Date(e);if(Number.isNaN(t.getTime()))throw new C(`Invalid date value for date-based query helper.`);return t}whereKey(e,t){return this.where({[e]:t})}whereIn(e,t){return this.where({[e]:{in:t}})}orderBy(e){return this.randomOrderEnabled=!1,this.args.orderBy=e,this}inRandomOrder(){return this.randomOrderEnabled=!0,this}reorder(e,t=`asc`){return this.args.orderBy=void 0,this.randomOrderEnabled=!1,e?this.orderBy({[e]:t}):this}latest(e=`createdAt`){return this.orderBy({[e]:`desc`})}oldest(e=`createdAt`){return this.orderBy({[e]:`asc`})}include(e){return this.args.include=e,this}with(e){let t=this.normalizeWith(e),n=Object.keys(t);return this.args.include={...this.args.include||{},...n.reduce((e,t)=>(e[t]=!0,e),{})},Object.entries(t).forEach(([e,t])=>{this.eagerLoads[e]=t}),this}has(e,t=`>=`,n=1,r){return this.relationFilters.push({relation:e,callback:r,operator:t,count:n,boolean:`AND`}),this}orHas(e,t=`>=`,n=1){return this.relationFilters.push({relation:e,operator:t,count:n,boolean:`OR`}),this}doesntHave(e,t){return this.has(e,`<`,1,t)}orDoesntHave(e){return this.orHas(e,`<`,1)}whereHas(e,t,n=`>=`,r=1){return this.has(e,n,r,t)}orWhereHas(e,t,n=`>=`,r=1){return this.relationFilters.push({relation:e,callback:t,operator:n,count:r,boolean:`OR`}),this}whereDoesntHave(e,t){return this.whereHas(e,t,`<`,1)}orWhereDoesntHave(e,t){return this.orWhereHas(e,t,`<`,1)}withCount(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`count`,relation:e})}),this}withExists(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`exists`,relation:e})}),this}withSum(e,t){return this.relationAggregates.push({type:`sum`,relation:e,column:t}),this}withAvg(e,t){return this.relationAggregates.push({type:`avg`,relation:e,column:t}),this}withMin(e,t){return this.relationAggregates.push({type:`min`,relation:e,column:t}),this}withMax(e,t){return this.relationAggregates.push({type:`max`,relation:e,column:t}),this}withTrashed(){return this.includeTrashed=!0,this.onlyTrashedRecords=!1,this}onlyTrashed(){return this.onlyTrashedRecords=!0,this.includeTrashed=!1,this}withoutTrashed(){return this.includeTrashed=!1,this.onlyTrashedRecords=!1,this}scope(e,...t){let n=`scope${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=this.model.prototype?.[n];if(typeof r!=`function`)throw new C(`Scope [${e}] is not defined.`);let i=r.call(void 0,this,...t);return i&&i!==this?i:this}when(e,t,n){let r=typeof e==`function`?e():e;return r?t(this,r):n?n(this,r):this}unless(e,t,n){let r=typeof e==`function`?e():e;return r?n?n(this,r):this:t(this,r)}tap(e){return e(this),this}pipe(e){return e(this)}select(e){return this.args.select=e,this}skip(e){return this.args.skip=e,this}offset(e){return this.skip(e)}take(e){return this.args.take=e,this}limit(e){return this.take(e)}forPage(e,t=15){let n=Math.max(1,e),r=Math.max(1,t);return this.skip((n-1)*r).take(r)}async get(){let e=new WeakMap,t=await this.delegate.findMany(this.buildFindArgs()),n=this.randomOrderEnabled?this.shuffleRows(t):t,r=this.model.hydrateMany(n),i=r;if(this.hasRelationFilters())if(this.hasOrRelationFilters()&&this.args.where){let t=new Set(r.map(e=>this.getModelId(e)).filter(e=>e!=null)),n=await this.delegate.findMany({...this.args,where:this.buildSoftDeleteOnlyWhere()}),a=this.model.hydrateMany(n);i=await this.filterModelsByRelationConstraints(a,e,t)}else i=await this.filterModelsByRelationConstraints(r,e);return this.hasRelationAggregates()&&await this.applyRelationAggregates(i,e),await Promise.all(i.map(async e=>{await e.load(this.eagerLoads)})),new J(i)}async first(){if(this.hasRelationFilters()||this.hasRelationAggregates())return(await this.get()).all()[0]??null;if(this.randomOrderEnabled){let e=await this.delegate.findMany(this.buildFindArgs());if(e.length===0)return null;let t=this.shuffleRows(e)[0];if(!t)return null;let n=this.model.hydrate(t);return await n.load(this.eagerLoads),n}let e=await this.delegate.findFirst(this.buildFindArgs());if(!e)return null;let t=this.model.hydrate(e);return await t.load(this.eagerLoads),t}async firstOrFail(){let e=await this.first();if(!e)throw new Y(`Record not found.`);return e}async find(e,t=`id`){return this.where({[t]:e}).first()}async findOr(e,t,n){let r=typeof t==`string`?t:`id`,i=typeof t==`function`?t:n;if(!i)throw new C(`findOr requires a fallback callback.`);return await this.find(e,r)||i()}async value(e){let t=await this.delegate.findFirst(this.buildFindArgs());return t?t[e]??null:null}async valueOrFail(e){let t=await this.value(e);if(t==null)throw new Y(`Record not found.`);return t}async pluck(e,t){let n=await this.delegate.findMany(this.buildFindArgs());return t?new J(n.sort((e,n)=>String(e[t]).localeCompare(String(n[t]))).map(t=>t[e])):new J(n.map(t=>t[e]))}async create(e){let t=await this.delegate.create({data:e});return this.model.hydrate(t)}async update(e){let t=this.buildWhere();if(!t)throw new C(`Update requires a where clause.`);let n=await this.resolveUniqueWhere(t),r=await this.delegate.update({where:n,data:e});return this.model.hydrate(r)}async delete(){let e=this.buildWhere();if(!e)throw new C(`Delete requires a where clause.`);let t=await this.resolveUniqueWhere(e),n=await this.delegate.delete({where:t});return this.model.hydrate(n)}async count(){return this.hasRelationFilters()?(await this.get()).all().length:this.delegate.count({where:this.buildWhere()})}async exists(){return this.hasRelationFilters()?await this.count()>0:await this.delegate.findFirst(this.buildFindArgs())!=null}async doesntExist(){return!await this.exists()}async existsOr(e){return await this.exists()?!0:e()}async doesntExistOr(e){return await this.doesntExist()?!0:e()}async min(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t<e?t:e)}async max(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t>e?t:e)}async sum(e){return(await this.delegate.findMany(this.buildFindArgs())).reduce((t,n)=>{let r=n[e],i=typeof r==`number`?r:Number(r);return Number.isFinite(i)?t+i:t},0)}async avg(e){let t=(await this.delegate.findMany(this.buildFindArgs())).map(t=>{let n=t[e];return typeof n==`number`?n:Number(n)}).filter(e=>Number.isFinite(e));return t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length}whereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new C(`Raw where clauses are not supported by the current adapter.`);return this.args.where=n.applyRawWhere(this.buildWhere(),e,t),this}orWhereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new C(`Raw where clauses are not supported by the current adapter.`);let r=n.applyRawWhere(void 0,e,t);return this.orWhere(r)}async paginate(e=1,t=15,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,e),i=Math.max(1,t),a=(await this.get()).all(),o=(r-1)*i;return new Q(new J(a.slice(o,o+i)),a.length,i,r,n)}let r=Math.max(1,e),i=Math.max(1,t),a=await this.count();return new Q(await this.clone().skip((r-1)*i).take(i).get(),a,i,r,n)}async simplePaginate(e=15,t=1,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,t),i=Math.max(1,e),a=(await this.get()).all(),o=(r-1)*i,s=a.slice(o,o+i),c=o+i<a.length;return new $(new J(s),i,r,c,n)}let r=Math.max(1,t),i=Math.max(1,e),a=await this.clone().skip((r-1)*i).take(i+1).get(),o=a.all().length>i;return new $(o?new J(a.all().slice(0,i)):a,i,r,o,n)}clone(){let t=new e(this.delegate,this.model);return t.args.where=this.args.where,t.args.include=this.args.include,t.args.orderBy=this.args.orderBy,t.args.select=this.args.select,t.args.skip=this.args.skip,t.args.take=this.args.take,t.includeTrashed=this.includeTrashed,t.onlyTrashedRecords=this.onlyTrashedRecords,t.randomOrderEnabled=this.randomOrderEnabled,this.relationFilters.forEach(e=>{t.relationFilters.push({...e})}),this.relationAggregates.forEach(e=>{t.relationAggregates.push({...e})}),Object.entries(this.eagerLoads).forEach(([e,n])=>{t.eagerLoads[e]=n}),t}normalizeWith(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}buildWhere(){let e=this.model.getSoftDeleteConfig();if(!e.enabled||this.includeTrashed)return this.args.where;let t=this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null};return this.args.where?{AND:[this.args.where,t]}:t}buildFindArgs(){return{...this.args,where:this.buildWhere()}}async resolveUniqueWhere(e){if(this.isUniqueWhere(e))return e;let t=await this.delegate.findFirst({where:e});if(!t)throw new C(`Record not found for update/delete operation.`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`id`))throw new C(`Unable to resolve a unique identifier for update/delete operation. Include an id in the query constraints.`);return{id:n.id}}isUniqueWhere(e){return Object.keys(e).length===1&&Object.prototype.hasOwnProperty.call(e,`id`)}shuffleRows(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}hasRelationFilters(){return this.relationFilters.length>0}hasOrRelationFilters(){return this.relationFilters.some(e=>e.boolean===`OR`)}hasRelationAggregates(){return this.relationAggregates.length>0}async filterModelsByRelationConstraints(e,t,n){return(await Promise.all(e.map(async e=>{let r=null;n&&(r=n.has(this.getModelId(e)));for(let n of this.relationFilters){let i=await this.resolveRelatedCount(e,n.relation,t,n.callback),a=this.compareCount(i,n.operator,n.count);r=r==null?a:n.boolean===`AND`?r&&a:r||a}return{model:e,passes:r??!0}}))).filter(e=>e.passes).map(e=>e.model)}getModelId(e){let t=e;if(typeof t.getAttribute!=`function`)return null;let n=t.getAttribute(`id`);return typeof n==`number`||typeof n==`string`?n:null}buildSoftDeleteOnlyWhere(){let e=this.model.getSoftDeleteConfig();if(e.enabled&&!this.includeTrashed)return this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null}}async applyRelationAggregates(e,t){let n=t??new WeakMap;await Promise.all(e.map(async e=>{for(let t of this.relationAggregates){let r=await this.resolveRelatedResults(e,t.relation,n),i=Array.isArray(r)?r:r?[r]:[],a=this.buildAggregateAttributeKey(t);if(t.type===`count`){this.assignAggregate(e,a,i.length);continue}if(t.type===`exists`){this.assignAggregate(e,a,i.length>0);continue}let o=i.map(e=>e.getAttribute(t.column)).filter(e=>e!=null);if(t.type===`sum`){let t=o.reduce((e,t)=>{let n=typeof t==`number`?t:Number(t);return Number.isFinite(n)?e+n:e},0);this.assignAggregate(e,a,t);continue}if(t.type===`avg`){let t=o.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)),n=t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length;this.assignAggregate(e,a,n);continue}if(t.type===`min`){let t=o.length===0?null:o.reduce((e,t)=>t<e?t:e);this.assignAggregate(e,a,t);continue}let s=o.length===0?null:o.reduce((e,t)=>t>e?t:e);this.assignAggregate(e,a,s)}}))}async resolveRelatedCount(e,t,n,r){let i=await this.resolveRelatedResults(e,t,n,r);return Array.isArray(i)?i.length:i?1:0}async resolveRelatedResults(e,t,n,r){let i=e,a=r??`__none__`,o=n.get(i);o||(o=new Map,n.set(i,o));let s=o.get(t);s||(s=new Map,o.set(t,s));let c=s.get(a);if(c)return await c;let l=(async()=>{let n=e[t];if(typeof n!=`function`)throw new C(`Relation [${t}] is not defined on the model.`);let i=n.call(e);if(r&&typeof i.constrain==`function`&&i.constrain(e=>r(e)??e),typeof i.get==`function`){let e=await i.get();return e instanceof J?e.all():e}if(typeof i.getResults==`function`){let e=await i.getResults();return e instanceof J?e.all():e}throw new C(`Relation [${t}] does not support result resolution.`)})();return s.set(a,l),await l}compareCount(e,t,n){return t===`>=`?e>=n:t===`>`?e>n:t===`=`?e===n:t===`!=`?e!==n:t===`<=`?e<=n:e<n}buildAggregateAttributeKey(e){let t=e.relation;if(e.type===`count`)return`${t}Count`;if(e.type===`exists`)return`${t}Exists`;let n=e.column?`${e.column.charAt(0).toUpperCase()}${e.column.slice(1)}`:``;return`${t}${`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}`}${n}`}assignAggregate(e,t,n){let r=e;if(typeof r.setAttribute==`function`){r.setAttribute(t,n);return}e[t]=n}},nt=class e{static factoryClass;static client;static delegate;static softDeletes=!1;static deletedAtColumn=`deletedAt`;static globalScopes={};static eventListeners={};casts={};hidden=[];visible=[];appends=[];attributes;constructor(e={}){return this.attributes={},this.fill(e),new Proxy(this,{get:(e,t,n)=>typeof t!=`string`||t in e?Reflect.get(e,t,n):e.getAttribute(t),set:(e,t,n,r)=>typeof t!=`string`||t in e?Reflect.set(e,t,n,r):(e.setAttribute(t,n),!0)})}static setClient(e){this.client=e}static setFactory(e){this.factoryClass=e}static factory(e){let t=this.factoryClass;if(!t)throw new C(`Factory is not configured for model [${this.name}].`);let n=new t;return typeof e==`number`&&n.count(e),n}static addGlobalScope(e,t){this.ensureOwnGlobalScopes(),this.globalScopes[e]=t}static removeGlobalScope(e){this.ensureOwnGlobalScopes(),delete this.globalScopes[e]}static clearGlobalScopes(){this.globalScopes={}}static on(e,t){this.ensureOwnEventListeners(),this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e]?.push(t)}static off(e,t){if(this.ensureOwnEventListeners(),!t){delete this.eventListeners[e];return}this.eventListeners[e]=(this.eventListeners[e]||[]).filter(e=>e!==t)}static clearEventListeners(){this.eventListeners={}}static getDelegate(e){Oe();let t=e||this.delegate||`${b(this.name).camel().plural()}`,n=[t,`${b(t).camel()}`,`${b(t).singular()}`,`${b(t).camel().singular()}`],r=ke(),i=n.map(e=>this.client?.[e]??r?.[e]).find(e=>q(e));if(!i)throw new C(`Database delegate [${t}] is not configured.`);return i}static query(){let e=new tt(this.getDelegate(),this),t=this;return t.ensureOwnGlobalScopes(),Object.values(t.globalScopes).forEach(t=>{let n=t(e);n&&n!==e&&(e=n)}),e}static withTrashed(){return this.query().withTrashed()}static onlyTrashed(){return this.query().onlyTrashed()}static scope(e,...t){return this.query().scope(e,...t)}static getSoftDeleteConfig(){return{enabled:this.softDeletes,column:this.deletedAtColumn}}static hydrate(e){return new this(e)}static hydrateMany(e){return e.map(e=>new this(e))}fill(e){return Object.entries(e).forEach(([e,t])=>{this.setAttribute(e,t)}),this}getAttribute(e){let t=this.resolveGetMutator(e),n=this.casts[e],r=this.attributes[e];return n&&(r=S(n).get(r)),t?t.call(this,r):r}setAttribute(e,t){let n=this.resolveSetMutator(e),r=this.casts[e],i=t;return n&&(i=n.call(this,i)),r&&(i=S(r).set(i)),this.attributes[e]=i,this}async save(){let t=this.getAttribute(`id`),n=this.getRawAttributes(),r=this.constructor;if(t==null){await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`creating`,this);let t=await r.query().create(n);return this.fill(t.getRawAttributes()),await e.dispatchEvent(r,`created`,this),await e.dispatchEvent(r,`saved`,this),this}await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`updating`,this);let i=await r.query().where({id:t}).update(n);return this.fill(i.getRawAttributes()),await e.dispatchEvent(r,`updated`,this),await e.dispatchEvent(r,`saved`,this),this}async delete(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`deleting`,this);let r=n.getSoftDeleteConfig();if(r.enabled){let i=await n.query().where({id:t}).update({[r.column]:new Date});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}let i=await n.query().where({id:t}).delete();return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}async forceDelete(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot force delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`forceDeleting`,this),await e.dispatchEvent(n,`deleting`,this);let r=await n.query().withTrashed().where({id:t}).delete();return this.fill(r.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),await e.dispatchEvent(n,`forceDeleted`,this),this}async restore(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot restore a model without an id.`);let n=this.constructor,r=n.getSoftDeleteConfig();if(!r.enabled)return this;await e.dispatchEvent(n,`restoring`,this);let i=await n.query().withTrashed().where({id:t}).update({[r.column]:null});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`restored`,this),this}async load(e){let t=this.normalizeRelationMap(e);return await Promise.all(Object.entries(t).map(async([e,t])=>{let n=this[e];if(typeof n!=`function`)return;let r=n.call(this);t&&r.constrain(t);let i=await r.getResults();this.attributes[e]=i})),this}getRawAttributes(){return{...this.attributes}}toObject(){let e=(this.visible.length>0?this.visible:Object.keys(this.attributes).filter(e=>!this.hidden.includes(e))).reduce((e,t)=>{let n=this.getAttribute(t);return n instanceof Date&&(n=n.toISOString()),e[t]=n,e},{});return this.appends.forEach(t=>{e[t]=this.getAttribute(t)}),e}toJSON(){return this.toObject()}hasOne(e,t,n=`id`){return new Xe(this,e,t,n)}hasMany(e,t,n=`id`){return new Je(this,e,t,n)}belongsTo(e,t,n=`id`){return new qe(this,e,t,n)}belongsToMany(e,t,n,r,i=`id`,a=`id`){return new Ke(this,e,t,n,r,i,a)}hasOneThrough(e,t,n,r,i=`id`,a=`id`){return new Ze(this,e,t,n,r,i,a)}hasManyThrough(e,t,n,r,i=`id`,a=`id`){return new Ye(this,e,t,n,r,i,a)}morphOne(e,t,n=`id`){return new $e(this,e,t,n)}morphMany(e,t,n=`id`){return new Qe(this,e,t,n)}morphToMany(e,t,n,r,i=`id`,a=`id`){return new et(this,e,t,n,r,i,a)}resolveGetMutator(e){let t=`get${b(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}resolveSetMutator(e){let t=`set${b(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}static ensureOwnGlobalScopes(){Object.prototype.hasOwnProperty.call(this,`globalScopes`)||(this.globalScopes={...this.globalScopes||{}})}static ensureOwnEventListeners(){Object.prototype.hasOwnProperty.call(this,`eventListeners`)||(this.eventListeners={...this.eventListeners||{}})}static async dispatchEvent(e,t,n){e.ensureOwnEventListeners();let r=e.eventListeners[t]||[];for(let e of r)await e(n)}normalizeRelationMap(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}};export{J as ArkormCollection,C as ArkormException,Ae as CliApp,je as InitCommand,Ve as InlineFactory,Q as LengthAwarePaginator,Me as MakeFactoryCommand,Ne as MakeMigrationCommand,Pe as MakeModelCommand,Fe as MakeSeederCommand,Ie as MigrateCommand,T as Migration,nt as Model,Be as ModelFactory,Y as ModelNotFoundException,Le as ModelsSyncCommand,ce as PRISMA_MODEL_REGEX,$ as Paginator,tt as QueryBuilder,se as SchemaBuilder,ze as SeedCommand,Re as Seeder,w as TableBuilder,Z as URLDriver,fe as applyAlterTableOperation,A as applyCreateTableOperation,pe as applyDropTableOperation,P as applyMigrationToPrismaSchema,me as applyOperationsToPrismaSchema,O as buildFieldLine,_e as buildMigrationSource,de as buildModelBlock,Ce as configureArkormRuntime,N as createMigrationTimestamp,Ue as createPrismaAdapter,We as createPrismaDelegateMap,Se as defineConfig,He as defineFactory,Oe as ensureArkormConfigLoading,D as escapeRegex,k as findModelBlock,ue as formatDefaultValue,ve as generateMigrationFile,G as getDefaultStubsPath,ye as getMigrationPlan,K as getRuntimePaginationURLDriverFactory,ke as getRuntimePrismaClient,H as getUserConfig,Ge as inferDelegateName,q as isDelegateLike,W as loadArkormConfig,M as pad,we as resetArkormRuntimeForTests,S as resolveCast,he as resolveMigrationClassName,le as resolvePrismaType,be as runMigrationWithPrisma,j as runPrismaCommand,ge as toMigrationFileSlug,E as toModelName};
|
|
50
|
+
`;var Y=class extends ae{},Be=class{amount=1;sequence=0;states=[];count(e){return this.amount=Math.max(1,Math.floor(e)),this}state(e){return this.states.push(e),this}make(e={}){let t=this.buildAttributes(e);return new this.model(t)}makeMany(e=this.amount,t={}){let n=Math.max(1,Math.floor(e));return Array.from({length:n},()=>this.make(t))}async create(e={}){let t=this.make(e);if(typeof t.save!=`function`)throw Error(`Factory model does not support save().`);return await t.save()}async createMany(e=this.amount,t={}){let n=this.makeMany(e,t);return await Promise.all(n.map(async e=>{if(typeof e.save!=`function`)throw Error(`Factory model does not support save().`);return await e.save()}))}buildAttributes(e){let t=this.sequence;this.sequence+=1;let n=this.definition(t);for(let e of this.states)n=e(n,t);return{...n,...e}}},Ve=class extends Be{model;constructor(e,t){super(),this.resolver=t,this.model=e}definition(e){return this.resolver(e)}};const He=(e,t)=>new Ve(e,t);var X=class extends C{constructor(e=`No query results for the given model.`){super(e),this.name=`ModelNotFoundException`}};function Ue(e){return Object.entries(e).reduce((e,[t,n])=>(J(n)&&(e[t]=n),e),{})}function We(e){return Ue(e)}function Ge(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}s`}var Z=class{constraint=null;constrain(e){if(!this.constraint)return this.constraint=e,this;let t=this.constraint;return this.constraint=n=>{let r=t(n)??n;return e(r)??r},this}where(e){return this.constrain(t=>t.where(e))}whereKey(e,t){return this.constrain(n=>n.whereKey(e,t))}whereIn(e,t){return this.constrain(n=>n.whereIn(e,t))}orderBy(e){return this.constrain(t=>t.orderBy(e))}include(e){return this.constrain(t=>t.include(e))}with(e){return this.constrain(t=>t.with(e))}select(e){return this.constrain(t=>t.select(e))}skip(e){return this.constrain(t=>t.skip(e))}take(e){return this.constrain(t=>t.take(e))}withTrashed(){return this.constrain(e=>e.withTrashed())}onlyTrashed(){return this.constrain(e=>e.onlyTrashed())}withoutTrashed(){return this.constrain(e=>e.withoutTrashed())}scope(e,...t){return this.constrain(n=>n.scope(e,...t))}applyConstraint(e){return this.constraint?this.constraint(e)??e:e}async get(){return this.getResults()}async first(){let e=await this.getResults();return e instanceof Y?e.all()[0]??null:e}},Ke=class extends Z{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.foreignPivotKey]:e}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:t}})).get()}},qe=class extends Z{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.ownerKey=r}async getResults(){let e=this.parent.getAttribute(this.foreignKey);return this.applyConstraint(this.related.query().where({[this.ownerKey]:e})).first()}},Je=class extends Z{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).get()}},Ye=class extends Z{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.firstKey]:e}})).map(e=>e[this.secondLocalKey]);return this.applyConstraint(this.related.query().where({[this.secondKey]:{in:t}})).get()}},Xe=class extends Z{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).first()}},Ze=class extends Z{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=await this.related.getDelegate(this.throughDelegate).findFirst({where:{[this.firstKey]:e}});return t?this.applyConstraint(this.related.query().where({[this.secondKey]:t[this.secondLocalKey]})).first():null}},Qe=class extends Z{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).get()}},$e=class extends Z{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).first()}},et=class extends Z{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.morphName=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=this.parent.constructor.name,n=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:n}})).get()}},Q=class e{static DEFAULT_PAGE_NAME=`page`;path;query;fragment;pageName;constructor(t={}){this.path=t.path??`/`,this.query=t.query??{},this.fragment=t.fragment??``,this.pageName=t.pageName??e.DEFAULT_PAGE_NAME}getPageName(){return this.pageName}url(e){let t=Math.max(1,e),[n,r=``]=this.path.split(`?`),i=new URLSearchParams(r);Object.entries(this.query).forEach(([e,t])=>{if(t==null){i.delete(e);return}i.set(e,String(t))}),i.set(this.pageName,String(t));let a=i.toString(),o=this.fragment.replace(/^#/,``);return!a&&!o?n:o?a?`${n}?${a}#${o}`:`${n}#${o}`:`${n}?${a}`}},tt=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=Math.max(1,Math.ceil(t/n)),o=t===0?null:(r-1)*n+1,s=t===0?null:Math.min(r*n,t);this.data=e;let c=q();this.urlDriver=c?c(i):new Q(i),this.meta={total:t,perPage:n,currentPage:r,lastPage:a,from:o,to:s}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.currentPage>=this.meta.lastPage?null:this.url(this.meta.currentPage+1)}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}firstPageUrl(){return this.url(1)}lastPageUrl(){return this.url(this.meta.lastPage)}toJSON(){return{data:this.data,meta:this.meta,links:{first:this.firstPageUrl(),last:this.lastPageUrl(),prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},$=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=e.all().length,o=a===0?null:(n-1)*t+1,s=a===0?null:(o??1)+a-1;this.data=e;let c=q();this.urlDriver=c?c(i):new Q(i),this.meta={perPage:t,currentPage:n,from:o,to:s,hasMorePages:r}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.hasMorePages?this.url(this.meta.currentPage+1):null}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}toJSON(){return{data:this.data,meta:this.meta,links:{prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},nt=class e{args={};eagerLoads={};includeTrashed=!1;onlyTrashedRecords=!1;randomOrderEnabled=!1;relationFilters=[];relationAggregates=[];constructor(e,t){this.delegate=e,this.model=t}where(e){return this.addLogicalWhere(`AND`,e)}orWhere(e){return this.addLogicalWhere(`OR`,e)}whereNot(e){return this.where({NOT:e})}orWhereNot(e){return this.orWhere({NOT:e})}whereNull(e){return this.where({[e]:null})}whereNotNull(e){return this.where({[e]:{not:null}})}whereBetween(e,t){let[n,r]=t;return this.where({[e]:{gte:n,lte:r}})}whereDate(e,t){let n=this.coerceDate(t),r=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),this.where({[e]:{gte:r,lt:i}})}whereMonth(e,t,n=new Date().getUTCFullYear()){let r=Math.min(12,Math.max(1,t)),i=new Date(Date.UTC(n,r-1,1)),a=new Date(Date.UTC(n,r,1));return this.where({[e]:{gte:i,lt:a}})}whereYear(e,t){let n=new Date(Date.UTC(t,0,1)),r=new Date(Date.UTC(t+1,0,1));return this.where({[e]:{gte:n,lt:r}})}whereKeyNot(e,t){return this.where({[e]:{not:t}})}orWhereIn(e,t){return this.orWhere({[e]:{in:t}})}whereNotIn(e,t){return this.where({[e]:{notIn:t}})}orWhereNotIn(e,t){return this.orWhere({[e]:{notIn:t}})}async firstWhere(e,t,n){let r=n!==void 0,i=r?t:`=`,a=r?n:t;return this.clone().where(this.buildComparisonWhere(e,i,a)).first()}addLogicalWhere(e,t){return this.args.where?(this.args.where={[e]:[this.args.where,t]},this):(this.args.where=t,this)}buildComparisonWhere(e,t,n){return t===`=`?{[e]:n}:t===`!=`?{[e]:{not:n}}:t===`>`?{[e]:{gt:n}}:t===`>=`?{[e]:{gte:n}}:t===`<`?{[e]:{lt:n}}:{[e]:{lte:n}}}coerceDate(e){let t=e instanceof Date?new Date(e.getTime()):new Date(e);if(Number.isNaN(t.getTime()))throw new C(`Invalid date value for date-based query helper.`);return t}whereKey(e,t){return this.where({[e]:t})}whereIn(e,t){return this.where({[e]:{in:t}})}orderBy(e){return this.randomOrderEnabled=!1,this.args.orderBy=e,this}inRandomOrder(){return this.randomOrderEnabled=!0,this}reorder(e,t=`asc`){return this.args.orderBy=void 0,this.randomOrderEnabled=!1,e?this.orderBy({[e]:t}):this}latest(e=`createdAt`){return this.orderBy({[e]:`desc`})}oldest(e=`createdAt`){return this.orderBy({[e]:`asc`})}include(e){return this.args.include=e,this}with(e){let t=this.normalizeWith(e),n=Object.keys(t);return this.args.include={...this.args.include||{},...n.reduce((e,t)=>(e[t]=!0,e),{})},Object.entries(t).forEach(([e,t])=>{this.eagerLoads[e]=t}),this}has(e,t=`>=`,n=1,r){return this.relationFilters.push({relation:e,callback:r,operator:t,count:n,boolean:`AND`}),this}orHas(e,t=`>=`,n=1){return this.relationFilters.push({relation:e,operator:t,count:n,boolean:`OR`}),this}doesntHave(e,t){return this.has(e,`<`,1,t)}orDoesntHave(e){return this.orHas(e,`<`,1)}whereHas(e,t,n=`>=`,r=1){return this.has(e,n,r,t)}orWhereHas(e,t,n=`>=`,r=1){return this.relationFilters.push({relation:e,callback:t,operator:n,count:r,boolean:`OR`}),this}whereDoesntHave(e,t){return this.whereHas(e,t,`<`,1)}orWhereDoesntHave(e,t){return this.orWhereHas(e,t,`<`,1)}withCount(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`count`,relation:e})}),this}withExists(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`exists`,relation:e})}),this}withSum(e,t){return this.relationAggregates.push({type:`sum`,relation:e,column:t}),this}withAvg(e,t){return this.relationAggregates.push({type:`avg`,relation:e,column:t}),this}withMin(e,t){return this.relationAggregates.push({type:`min`,relation:e,column:t}),this}withMax(e,t){return this.relationAggregates.push({type:`max`,relation:e,column:t}),this}withTrashed(){return this.includeTrashed=!0,this.onlyTrashedRecords=!1,this}onlyTrashed(){return this.onlyTrashedRecords=!0,this.includeTrashed=!1,this}withoutTrashed(){return this.includeTrashed=!1,this.onlyTrashedRecords=!1,this}scope(e,...t){let n=`scope${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=this.model.prototype?.[n];if(typeof r!=`function`)throw new C(`Scope [${e}] is not defined.`);let i=r.call(void 0,this,...t);return i&&i!==this?i:this}when(e,t,n){let r=typeof e==`function`?e():e;return r?t(this,r):n?n(this,r):this}unless(e,t,n){let r=typeof e==`function`?e():e;return r?n?n(this,r):this:t(this,r)}tap(e){return e(this),this}pipe(e){return e(this)}select(e){return this.args.select=e,this}skip(e){return this.args.skip=e,this}offset(e){return this.skip(e)}take(e){return this.args.take=e,this}limit(e){return this.take(e)}forPage(e,t=15){let n=Math.max(1,e),r=Math.max(1,t);return this.skip((n-1)*r).take(r)}async get(){let e=new WeakMap,t=await this.delegate.findMany(this.buildFindArgs()),n=this.randomOrderEnabled?this.shuffleRows(t):t,r=this.model.hydrateMany(n),i=r;if(this.hasRelationFilters())if(this.hasOrRelationFilters()&&this.args.where){let t=new Set(r.map(e=>this.getModelId(e)).filter(e=>e!=null)),n=await this.delegate.findMany({...this.args,where:this.buildSoftDeleteOnlyWhere()}),a=this.model.hydrateMany(n);i=await this.filterModelsByRelationConstraints(a,e,t)}else i=await this.filterModelsByRelationConstraints(r,e);return this.hasRelationAggregates()&&await this.applyRelationAggregates(i,e),await Promise.all(i.map(async e=>{await e.load(this.eagerLoads)})),new Y(i)}async first(){if(this.hasRelationFilters()||this.hasRelationAggregates())return(await this.get()).all()[0]??null;if(this.randomOrderEnabled){let e=await this.delegate.findMany(this.buildFindArgs());if(e.length===0)return null;let t=this.shuffleRows(e)[0];if(!t)return null;let n=this.model.hydrate(t);return await n.load(this.eagerLoads),n}let e=await this.delegate.findFirst(this.buildFindArgs());if(!e)return null;let t=this.model.hydrate(e);return await t.load(this.eagerLoads),t}async firstOrFail(){let e=await this.first();if(!e)throw new X(`Record not found.`);return e}async find(e,t=`id`){return this.where({[t]:e}).first()}async findOr(e,t,n){let r=typeof t==`string`?t:`id`,i=typeof t==`function`?t:n;if(!i)throw new C(`findOr requires a fallback callback.`);return await this.find(e,r)||i()}async value(e){let t=await this.delegate.findFirst(this.buildFindArgs());return t?t[e]??null:null}async valueOrFail(e){let t=await this.value(e);if(t==null)throw new X(`Record not found.`);return t}async pluck(e,t){let n=await this.delegate.findMany(this.buildFindArgs());return t?new Y(n.sort((e,n)=>String(e[t]).localeCompare(String(n[t]))).map(t=>t[e])):new Y(n.map(t=>t[e]))}async create(e){let t=await this.delegate.create({data:e});return this.model.hydrate(t)}async update(e){let t=this.buildWhere();if(!t)throw new C(`Update requires a where clause.`);let n=await this.resolveUniqueWhere(t),r=await this.delegate.update({where:n,data:e});return this.model.hydrate(r)}async delete(){let e=this.buildWhere();if(!e)throw new C(`Delete requires a where clause.`);let t=await this.resolveUniqueWhere(e),n=await this.delegate.delete({where:t});return this.model.hydrate(n)}async count(){return this.hasRelationFilters()?(await this.get()).all().length:this.delegate.count({where:this.buildWhere()})}async exists(){return this.hasRelationFilters()?await this.count()>0:await this.delegate.findFirst(this.buildFindArgs())!=null}async doesntExist(){return!await this.exists()}async existsOr(e){return await this.exists()?!0:e()}async doesntExistOr(e){return await this.doesntExist()?!0:e()}async min(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t<e?t:e)}async max(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t>e?t:e)}async sum(e){return(await this.delegate.findMany(this.buildFindArgs())).reduce((t,n)=>{let r=n[e],i=typeof r==`number`?r:Number(r);return Number.isFinite(i)?t+i:t},0)}async avg(e){let t=(await this.delegate.findMany(this.buildFindArgs())).map(t=>{let n=t[e];return typeof n==`number`?n:Number(n)}).filter(e=>Number.isFinite(e));return t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length}whereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new C(`Raw where clauses are not supported by the current adapter.`);return this.args.where=n.applyRawWhere(this.buildWhere(),e,t),this}orWhereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new C(`Raw where clauses are not supported by the current adapter.`);let r=n.applyRawWhere(void 0,e,t);return this.orWhere(r)}async paginate(e=1,t=15,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,e),i=Math.max(1,t),a=(await this.get()).all(),o=(r-1)*i;return new tt(new Y(a.slice(o,o+i)),a.length,i,r,n)}let r=Math.max(1,e),i=Math.max(1,t),a=await this.count();return new tt(await this.clone().skip((r-1)*i).take(i).get(),a,i,r,n)}async simplePaginate(e=15,t=1,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,t),i=Math.max(1,e),a=(await this.get()).all(),o=(r-1)*i,s=a.slice(o,o+i),c=o+i<a.length;return new $(new Y(s),i,r,c,n)}let r=Math.max(1,t),i=Math.max(1,e),a=await this.clone().skip((r-1)*i).take(i+1).get(),o=a.all().length>i;return new $(o?new Y(a.all().slice(0,i)):a,i,r,o,n)}clone(){let t=new e(this.delegate,this.model);return t.args.where=this.args.where,t.args.include=this.args.include,t.args.orderBy=this.args.orderBy,t.args.select=this.args.select,t.args.skip=this.args.skip,t.args.take=this.args.take,t.includeTrashed=this.includeTrashed,t.onlyTrashedRecords=this.onlyTrashedRecords,t.randomOrderEnabled=this.randomOrderEnabled,this.relationFilters.forEach(e=>{t.relationFilters.push({...e})}),this.relationAggregates.forEach(e=>{t.relationAggregates.push({...e})}),Object.entries(this.eagerLoads).forEach(([e,n])=>{t.eagerLoads[e]=n}),t}normalizeWith(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}buildWhere(){let e=this.model.getSoftDeleteConfig();if(!e.enabled||this.includeTrashed)return this.args.where;let t=this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null};return this.args.where?{AND:[this.args.where,t]}:t}buildFindArgs(){return{...this.args,where:this.buildWhere()}}async resolveUniqueWhere(e){if(this.isUniqueWhere(e))return e;let t=await this.delegate.findFirst({where:e});if(!t)throw new C(`Record not found for update/delete operation.`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`id`))throw new C(`Unable to resolve a unique identifier for update/delete operation. Include an id in the query constraints.`);return{id:n.id}}isUniqueWhere(e){return Object.keys(e).length===1&&Object.prototype.hasOwnProperty.call(e,`id`)}shuffleRows(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}hasRelationFilters(){return this.relationFilters.length>0}hasOrRelationFilters(){return this.relationFilters.some(e=>e.boolean===`OR`)}hasRelationAggregates(){return this.relationAggregates.length>0}async filterModelsByRelationConstraints(e,t,n){return(await Promise.all(e.map(async e=>{let r=null;n&&(r=n.has(this.getModelId(e)));for(let n of this.relationFilters){let i=await this.resolveRelatedCount(e,n.relation,t,n.callback),a=this.compareCount(i,n.operator,n.count);r=r==null?a:n.boolean===`AND`?r&&a:r||a}return{model:e,passes:r??!0}}))).filter(e=>e.passes).map(e=>e.model)}getModelId(e){let t=e;if(typeof t.getAttribute!=`function`)return null;let n=t.getAttribute(`id`);return typeof n==`number`||typeof n==`string`?n:null}buildSoftDeleteOnlyWhere(){let e=this.model.getSoftDeleteConfig();if(e.enabled&&!this.includeTrashed)return this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null}}async applyRelationAggregates(e,t){let n=t??new WeakMap;await Promise.all(e.map(async e=>{for(let t of this.relationAggregates){let r=await this.resolveRelatedResults(e,t.relation,n),i=Array.isArray(r)?r:r?[r]:[],a=this.buildAggregateAttributeKey(t);if(t.type===`count`){this.assignAggregate(e,a,i.length);continue}if(t.type===`exists`){this.assignAggregate(e,a,i.length>0);continue}let o=i.map(e=>e.getAttribute(t.column)).filter(e=>e!=null);if(t.type===`sum`){let t=o.reduce((e,t)=>{let n=typeof t==`number`?t:Number(t);return Number.isFinite(n)?e+n:e},0);this.assignAggregate(e,a,t);continue}if(t.type===`avg`){let t=o.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)),n=t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length;this.assignAggregate(e,a,n);continue}if(t.type===`min`){let t=o.length===0?null:o.reduce((e,t)=>t<e?t:e);this.assignAggregate(e,a,t);continue}let s=o.length===0?null:o.reduce((e,t)=>t>e?t:e);this.assignAggregate(e,a,s)}}))}async resolveRelatedCount(e,t,n,r){let i=await this.resolveRelatedResults(e,t,n,r);return Array.isArray(i)?i.length:i?1:0}async resolveRelatedResults(e,t,n,r){let i=e,a=r??`__none__`,o=n.get(i);o||(o=new Map,n.set(i,o));let s=o.get(t);s||(s=new Map,o.set(t,s));let c=s.get(a);if(c)return await c;let l=(async()=>{let n=e[t];if(typeof n!=`function`)throw new C(`Relation [${t}] is not defined on the model.`);let i=n.call(e);if(r&&typeof i.constrain==`function`&&i.constrain(e=>r(e)??e),typeof i.get==`function`){let e=await i.get();return e instanceof Y?e.all():e}if(typeof i.getResults==`function`){let e=await i.getResults();return e instanceof Y?e.all():e}throw new C(`Relation [${t}] does not support result resolution.`)})();return s.set(a,l),await l}compareCount(e,t,n){return t===`>=`?e>=n:t===`>`?e>n:t===`=`?e===n:t===`!=`?e!==n:t===`<=`?e<=n:e<n}buildAggregateAttributeKey(e){let t=e.relation;if(e.type===`count`)return`${t}Count`;if(e.type===`exists`)return`${t}Exists`;let n=e.column?`${e.column.charAt(0).toUpperCase()}${e.column.slice(1)}`:``;return`${t}${`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}`}${n}`}assignAggregate(e,t,n){let r=e;if(typeof r.setAttribute==`function`){r.setAttribute(t,n);return}e[t]=n}},rt=class e{static factoryClass;static client;static delegate;static softDeletes=!1;static deletedAtColumn=`deletedAt`;static globalScopes={};static eventListeners={};casts={};hidden=[];visible=[];appends=[];attributes;constructor(e={}){return this.attributes={},this.fill(e),new Proxy(this,{get:(e,t,n)=>typeof t!=`string`||t in e?Reflect.get(e,t,n):e.getAttribute(t),set:(e,t,n,r)=>typeof t!=`string`||t in e?Reflect.set(e,t,n,r):(e.setAttribute(t,n),!0)})}static setClient(e){this.client=e}static setFactory(e){this.factoryClass=e}static factory(e){let t=this.factoryClass;if(!t)throw new C(`Factory is not configured for model [${this.name}].`);let n=new t;return typeof e==`number`&&n.count(e),n}static addGlobalScope(e,t){this.ensureOwnGlobalScopes(),this.globalScopes[e]=t}static removeGlobalScope(e){this.ensureOwnGlobalScopes(),delete this.globalScopes[e]}static clearGlobalScopes(){this.globalScopes={}}static on(e,t){this.ensureOwnEventListeners(),this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e]?.push(t)}static off(e,t){if(this.ensureOwnEventListeners(),!t){delete this.eventListeners[e];return}this.eventListeners[e]=(this.eventListeners[e]||[]).filter(e=>e!==t)}static clearEventListeners(){this.eventListeners={}}static getDelegate(e){Oe();let t=e||this.delegate||`${b(this.name).camel().plural()}`,n=[t,`${b(t).camel()}`,`${b(t).singular()}`,`${b(t).camel().singular()}`],r=ke(),i=n.map(e=>this.client?.[e]??r?.[e]).find(e=>J(e));if(!i)throw new C(`Database delegate [${t}] is not configured.`);return i}static query(){let e=new nt(this.getDelegate(),this),t=this;return t.ensureOwnGlobalScopes(),Object.values(t.globalScopes).forEach(t=>{let n=t(e);n&&n!==e&&(e=n)}),e}static withTrashed(){return this.query().withTrashed()}static onlyTrashed(){return this.query().onlyTrashed()}static scope(e,...t){return this.query().scope(e,...t)}static getSoftDeleteConfig(){return{enabled:this.softDeletes,column:this.deletedAtColumn}}static hydrate(e){return new this(e)}static hydrateMany(e){return e.map(e=>new this(e))}fill(e){return Object.entries(e).forEach(([e,t])=>{this.setAttribute(e,t)}),this}getAttribute(e){let t=this.resolveGetMutator(e),n=this.casts[e],r=this.attributes[e];return n&&(r=S(n).get(r)),t?t.call(this,r):r}setAttribute(e,t){let n=this.resolveSetMutator(e),r=this.casts[e],i=t;return n&&(i=n.call(this,i)),r&&(i=S(r).set(i)),this.attributes[e]=i,this}async save(){let t=this.getAttribute(`id`),n=this.getRawAttributes(),r=this.constructor;if(t==null){await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`creating`,this);let t=await r.query().create(n);return this.fill(t.getRawAttributes()),await e.dispatchEvent(r,`created`,this),await e.dispatchEvent(r,`saved`,this),this}await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`updating`,this);let i=await r.query().where({id:t}).update(n);return this.fill(i.getRawAttributes()),await e.dispatchEvent(r,`updated`,this),await e.dispatchEvent(r,`saved`,this),this}async delete(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`deleting`,this);let r=n.getSoftDeleteConfig();if(r.enabled){let i=await n.query().where({id:t}).update({[r.column]:new Date});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}let i=await n.query().where({id:t}).delete();return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}async forceDelete(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot force delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`forceDeleting`,this),await e.dispatchEvent(n,`deleting`,this);let r=await n.query().withTrashed().where({id:t}).delete();return this.fill(r.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),await e.dispatchEvent(n,`forceDeleted`,this),this}async restore(){let t=this.getAttribute(`id`);if(t==null)throw new C(`Cannot restore a model without an id.`);let n=this.constructor,r=n.getSoftDeleteConfig();if(!r.enabled)return this;await e.dispatchEvent(n,`restoring`,this);let i=await n.query().withTrashed().where({id:t}).update({[r.column]:null});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`restored`,this),this}async load(e){let t=this.normalizeRelationMap(e);return await Promise.all(Object.entries(t).map(async([e,t])=>{let n=this[e];if(typeof n!=`function`)return;let r=n.call(this);t&&r.constrain(t);let i=await r.getResults();this.attributes[e]=i})),this}getRawAttributes(){return{...this.attributes}}toObject(){let e=(this.visible.length>0?this.visible:Object.keys(this.attributes).filter(e=>!this.hidden.includes(e))).reduce((e,t)=>{let n=this.getAttribute(t);return n instanceof Date&&(n=n.toISOString()),e[t]=n,e},{});return this.appends.forEach(t=>{e[t]=this.getAttribute(t)}),e}toJSON(){return this.toObject()}hasOne(e,t,n=`id`){return new Xe(this,e,t,n)}hasMany(e,t,n=`id`){return new Je(this,e,t,n)}belongsTo(e,t,n=`id`){return new qe(this,e,t,n)}belongsToMany(e,t,n,r,i=`id`,a=`id`){return new Ke(this,e,t,n,r,i,a)}hasOneThrough(e,t,n,r,i=`id`,a=`id`){return new Ze(this,e,t,n,r,i,a)}hasManyThrough(e,t,n,r,i=`id`,a=`id`){return new Ye(this,e,t,n,r,i,a)}morphOne(e,t,n=`id`){return new $e(this,e,t,n)}morphMany(e,t,n=`id`){return new Qe(this,e,t,n)}morphToMany(e,t,n,r,i=`id`,a=`id`){return new et(this,e,t,n,r,i,a)}resolveGetMutator(e){let t=`get${b(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}resolveSetMutator(e){let t=`set${b(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}static ensureOwnGlobalScopes(){Object.prototype.hasOwnProperty.call(this,`globalScopes`)||(this.globalScopes={...this.globalScopes||{}})}static ensureOwnEventListeners(){Object.prototype.hasOwnProperty.call(this,`eventListeners`)||(this.eventListeners={...this.eventListeners||{}})}static async dispatchEvent(e,t,n){e.ensureOwnEventListeners();let r=e.eventListeners[t]||[];for(let e of r)await e(n)}normalizeRelationMap(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}};export{Y as ArkormCollection,C as ArkormException,Ae as CliApp,je as InitCommand,Ve as InlineFactory,tt as LengthAwarePaginator,Me as MakeFactoryCommand,Ne as MakeMigrationCommand,Pe as MakeModelCommand,Fe as MakeSeederCommand,Ie as MigrateCommand,w as Migration,rt as Model,Be as ModelFactory,X as ModelNotFoundException,Le as ModelsSyncCommand,ce as PRISMA_MODEL_REGEX,$ as Paginator,nt as QueryBuilder,se as SchemaBuilder,ze as SeedCommand,Re as Seeder,T as TableBuilder,Q as URLDriver,de as applyAlterTableOperation,M as applyCreateTableOperation,fe as applyDropTableOperation,I as applyMigrationToPrismaSchema,pe as applyOperationsToPrismaSchema,k as buildFieldLine,A as buildIndexLine,ge as buildMigrationSource,ue as buildModelBlock,Ce as configureArkormRuntime,F as createMigrationTimestamp,Ue as createPrismaAdapter,We as createPrismaDelegateMap,Se as defineConfig,He as defineFactory,Oe as ensureArkormConfigLoading,D as escapeRegex,j as findModelBlock,O as formatDefaultValue,_e as generateMigrationFile,K as getDefaultStubsPath,ve as getMigrationPlan,q as getRuntimePaginationURLDriverFactory,ke as getRuntimePrismaClient,U as getUserConfig,Ge as inferDelegateName,J as isDelegateLike,G as loadArkormConfig,P as pad,we as resetArkormRuntimeForTests,S as resolveCast,me as resolveMigrationClassName,le as resolvePrismaType,ye as runMigrationWithPrisma,N as runPrismaCommand,he as toMigrationFileSlug,E as toModelName};
|