@stacksjs/orm 0.75.685 → 0.75.690

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.
@@ -23,7 +23,7 @@ export {}
23
23
 
24
24
  export interface FrameworkSchema {
25
25
  `;const FRAMEWORK_FOOTER=`}
26
- `;function headerFor(target){return target==="framework"?FRAMEWORK_HEADER:APP_HEADER}function footerFor(target){return target==="framework"?FRAMEWORK_FOOTER:APP_FOOTER}async function loadModelsFrom(dir,recursive,failures=[]){const out=[];if(!fs.existsSync(dir))return out;const entries=fs.readdirSync(dir,{withFileTypes:true});for(const entry of entries){const fullPath=path.join(dir,entry.name);if(entry.isDirectory()){if(recursive){const sub=await loadModelsFrom(fullPath,true,failures);out.push(...sub)}continue}if(!entry.name.endsWith(".ts"))continue;if(entry.name.startsWith("_")||entry.name.startsWith("index"))continue;try{const module=await(path.isAbsolute(fullPath)?import(fullPath):import(path.resolve(fullPath)));const def=module.default||module;if(def?.name&&(def.attributes||def.table)){out.push({filePath:fullPath,model:def})}}catch(err){failures.push({file:fullPath,error:err.message})}}return out}export async function buildDatabaseSchema(options={}){const dialect=resolveDialect(options.dialect);const modelsDir=options.modelsDir??path.userModelsPath();const defaultsDir=options.defaultsDir??path.frameworkPath("defaults/app/Models");const outFile=options.outFile??path.projectPath("database/types.d.ts");const errors=[];const allModels=[];for(const[dir,recursive]of[[modelsDir,false],[defaultsDir,true]]){try{const found=await loadModelsFrom(dir,recursive,errors);allModels.push(...found)}catch(err){errors.push({file:dir,error:err.message})}}const byName=new Map;for(const item of allModels){byName.set(item.model.name??path.basename(item.filePath).replace(/\.ts$/,""),item)}for(const item of allModels){if(item.filePath.startsWith(modelsDir)){byName.set(item.model.name??path.basename(item.filePath).replace(/\.ts$/,""),item)}}const tables=[];for(const[name,{model}]of byName){const tableName=model.table??`${snakeCase(name)}s`;const columns={...deriveSystemColumns(model,dialect),...deriveAttributeColumns(model,dialect),...deriveFkColumns(model)};tables.push({table:tableName,model:name,columns})}const pivotByTable=new Map;for(const[name,{model}]of byName){for(const pivot of derivePivotTables(name,model,dialect)){if(pivotByTable.has(pivot.table))continue;pivotByTable.set(pivot.table,{table:pivot.table,model:`(${pivot.table} pivot)`,columns:pivot.columns})}}tables.push(...pivotByTable.values());if(options.migrationsDir!==false){const migrationsDir=options.migrationsDir??path.resolve(path.dirname(outFile),"migrations");const owned=new Set(tables.map((entry)=>entry.table));const derived=deriveMigrationTables(migrationsDir,dialect);for(const entry of derived.tables){if(owned.has(entry.table))continue;owned.add(entry.table);tables.push({table:entry.table,model:`(${entry.table} migration)`,columns:entry.columns})}errors.push(...derived.errors)}tables.sort((a,b)=>a.table.localeCompare(b.table));const target=options.target??"app";const indent=target==="framework"?1:2;const body=tables.map((t)=>renderTableEntry(t.table,t.columns,indent)).join(`
26
+ `;function headerFor(target){return target==="framework"?FRAMEWORK_HEADER:APP_HEADER}function footerFor(target){return target==="framework"?FRAMEWORK_FOOTER:APP_FOOTER}async function loadModelsFrom(dir,recursive,failures=[]){const out=[];if(!fs.existsSync(dir))return out;const entries=fs.readdirSync(dir,{withFileTypes:true});for(const entry of entries){const fullPath=path.join(dir,entry.name);if(entry.isDirectory()){if(recursive){const sub=await loadModelsFrom(fullPath,true,failures);out.push(...sub)}continue}if(!entry.name.endsWith(".ts"))continue;if(entry.name.startsWith("_")||entry.name.startsWith("index"))continue;try{const module=await(path.isAbsolute(fullPath)?import(fullPath):import(path.resolve(fullPath)));const def=module.default||module;if(def?.name&&(def.attributes||def.table)){out.push({filePath:fullPath,model:def})}}catch(err){failures.push({file:fullPath,error:err.message})}}return out}export async function buildDatabaseSchema(options={}){const dialect=resolveDialect(options.dialect);const modelsDir=options.modelsDir??path.userModelsPath();const defaultsDir=options.defaultsDir??path.frameworkPath("defaults/app/Models");const outFile=options.outFile??path.projectPath("database/types.d.ts");const errors=[];const allModels=[];for(const[dir,recursive]of[[modelsDir,false],[defaultsDir,true]]){try{const found=await loadModelsFrom(dir,recursive,errors);allModels.push(...found)}catch(err){errors.push({file:dir,error:err.message})}}const byName=new Map;for(const item of allModels){byName.set(item.model.name??path.basename(item.filePath).replace(/\.ts$/,""),item)}for(const item of allModels){if(item.filePath.startsWith(modelsDir)){byName.set(item.model.name??path.basename(item.filePath).replace(/\.ts$/,""),item)}}const tables=[];for(const[name,{model}]of byName){const tableName=model.table??`${snakeCase(name)}s`;const columns={...deriveSystemColumns(model,dialect),...deriveAttributeColumns(model,dialect),...deriveFkColumns(model)};tables.push({table:tableName,model:name,columns})}const pivotByTable=new Map;for(const[name,{model}]of byName){for(const pivot of derivePivotTables(name,model,dialect)){if(pivotByTable.has(pivot.table))continue;pivotByTable.set(pivot.table,{table:pivot.table,model:`(${pivot.table} pivot)`,columns:pivot.columns})}}tables.push(...pivotByTable.values());if(options.migrationsDir!==false){const migrationsDir=options.migrationsDir??path.resolve(path.dirname(outFile),"migrations");const owned=new Map(tables.map((entry)=>[entry.table,entry]));const derived=deriveMigrationTables(migrationsDir,dialect);for(const entry of derived.tables){const owner=owned.get(entry.table);if(owner){for(const[column,type]of Object.entries(entry.columns)){if(!(column in owner.columns))owner.columns[column]=type}continue}const table={table:entry.table,model:`(${entry.table} migration)`,columns:entry.columns};owned.set(entry.table,table);tables.push(table)}errors.push(...derived.errors)}tables.sort((a,b)=>a.table.localeCompare(b.table));const target=options.target??"app";const indent=target==="framework"?1:2;const body=tables.map((t)=>renderTableEntry(t.table,t.columns,indent)).join(`
27
27
  `);const content=`${headerFor(target)}${body}
28
28
  ${footerFor(target)}`;if(!options.dryRun&&(!options.strict||errors.length===0)&&await Bun.file(outFile).text().catch(()=>{return})!==content){const dir=path.dirname(outFile);if(!fs.existsSync(dir))fs.mkdirSync(dir,{recursive:true});options.guard?.beforeWrite(outFile);fs.writeFileSync(outFile,content,"utf-8");options.guard?.afterWrite(outFile);log.success(`[generate:db-types] wrote ${tables.length} table(s) to ${outFile}`)}return{outFile,tables,errors,content}}export function renderDatabaseTypeFile(tables,target="app"){const body=[...tables].sort((a,b)=>a.table.localeCompare(b.table)).map((t)=>renderTableEntry(t.table,t.columns,target==="framework"?1:2)).join(`
29
29
  `);return`${headerFor(target)}${body}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"@stacksjs/validation/runtime";import{isCompiledBinary}from"@stacksjs/path";export*from"./utils/prunable";export{collectEncryptedAttributes,decryptRow,decryptRows,decryptValue,decryptValueInPlace,encryptedColumns,encryptRow,encryptValue,isEncrypted}from"./utils/encrypted";export{setAuditUser,createAuditMethods}from"./traits/audit";export{createCommentableMethods}from"./traits/commentable";export{createTaggableMethods}from"./traits/taggable";export{createCategorizableMethods}from"./traits/categorizable";export{createLikeableMethods}from"./traits/likeable";export{BILLABLE_INSTANCE_METHODS,isBillable,SubscriptionNotOwnedError}from"./traits/billable";export{filterFillable,getWritableFields,isUniqueViolation,mapWriteError,toSnakeCaseKeys}from"./auto-crud";export{customerOwnership,parentOwnership,selfOwnership,siteOwnership,teamMembershipOwnership}from"./ownership";export*from"./batch-loader";export*from"./db";export*from"./subquery";export*from"./transaction";export*from"./locked-row";export*from"./row-token";export*from"./gdpr";export*from"./model-types";export*from"./types";export*from"@stacksjs/model-meta";export*from"./define-model";export*from"./extend-model";export{buildDatabaseSchema,renderDatabaseTypeFile}from"./generate-database-schema";export{isCursorPaginator,isPaginator,isSimplePaginator,toCursorPaginator,toPaginator,toSimplePaginator}from"@stacksjs/pagination";export{enrichPaginatorUrls,parseCursor,resolveCursorArgs,resolvePageArgs}from"./paginator-request";async function importDefault(modulePath){for(let attempt=0;;attempt++){const mod=await import(modulePath);try{return mod.default}catch(err){if(attempt<5&&err instanceof ReferenceError&&/before initialization/.test(err.message)){await new Promise((resolve)=>setTimeout(resolve,0));continue}throw err}}}let announcedCompiledSkip=false;async function loadUserlandModel(modelName,subdirs=[""]){if(isCompiledBinary()){if(!announcedCompiledSkip){announcedCompiledSkip=true;console.debug("[orm] running from a compiled binary, so framework default models are not probed on disk; models this app uses are bundled.")}return null}const{path}=await import("@stacksjs/path");const userPath=path.userModelsPath(`${modelName}.ts`);try{if(await Bun.file(userPath).exists()){return await importDefault(userPath)}}catch(err){console.error(`[orm] Failed to import userland model ${modelName} from ${userPath} - falling back to framework default. Reason:`,err)}for(const sub of subdirs){const prefix=sub?`${sub}/`:"";const defaultPath=path.frameworkPath(`defaults/app/Models/${prefix}${modelName}.ts`);try{if(await Bun.file(defaultPath).exists()){return await importDefault(defaultPath)}}catch(err){console.error(`[orm] Failed to import framework default model ${modelName} from ${defaultPath} - trying next subdir. Reason:`,err)}}return null}const _loaded={};let _modelsSettled=false;const QUERY_ENTRYPOINTS=new Set(["where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","latest","oldest","limit","take","skip","select","find","findOrFail","findMany","first","firstOrFail","all","get","paginate","count","sum","avg","min","max","create","createMany","firstOrCreate","updateOrCreate","save","update","updateMany","delete","destroy","remove","truncate"]);function featureGateFor(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export function frameworkModelFeature(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export class ModelUnavailableError extends Error{model;feature;name="ModelUnavailableError";constructor(model,feature){super(`Model "${model}" is not available in this process. ${feature?`The '${feature}' feature is off, so this model was never loaded - set \`enabled: true\` in config/${feature}.ts to use it.`:`No model file for it was found under app/Models or the framework defaults.`}`);this.model=model;this.feature=feature}}function unavailableModel(name){return new ModelUnavailableError(name,featureGateFor(name))}let _readyResolve=()=>{};export const ormReady=new Promise((resolve)=>{_readyResolve=resolve});function lazyModel(name){return new Proxy(function _modelStub(){},{get(_target,prop){if(prop==="then")return;const m=_loaded[name];if(m==null){if(_modelsSettled&&typeof prop==="string"&&QUERY_ENTRYPOINTS.has(prop))throw unavailableModel(name);return}const value=m[prop];return typeof value==="function"?value.bind(m):value},set(_target,prop,value){const m=_loaded[name];if(m==null)return false;m[prop]=value;return true},has(_target,prop){const m=_loaded[name];return m==null?false:(prop in m)},apply(_target,thisArg,args){const m=_loaded[name];if(m==null||typeof m!=="function")return;return m.apply(thisArg,args)}})}export const User=lazyModel("User");export const Job=lazyModel("Job");export const QueueWorker=lazyModel("QueueWorker");export const FailedJob=lazyModel("FailedJob");const FRAMEWORK_MODEL_MANIFEST=[["QueueWorker",[""],"queue"],["Referral",[""],"auth"],["ReferralCode",[""],"auth"],["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Categorizable",["Content"],"cms"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["GdprRequest",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardAttachment",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["FeedbackToken",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["StorageItem",[""],"dashboard"],["StorageItemTask",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["Discount",["commerce"],"commerce"],["PostPurchaseOffer",["commerce"],"commerce"],["PostPurchaseOfferResponse",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["LicenseActivation",["commerce"],"commerce"],["LicenseSeat",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["PaymentWebhookEvent",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{const{feature}=await import("@stacksjs/config");const userModel=await loadUserlandModel("User");if(userModel)_loaded.User=userModel;if(feature("queue")){const job=await loadUserlandModel("Job");if(job)_loaded.Job=job;const failedJob=await loadUserlandModel("FailedJob");if(failedJob)_loaded.FailedJob=failedJob}for(const[name,subdirs,featureFlag]of FRAMEWORK_MODEL_MANIFEST){if(!feature(featureFlag))continue;const M=await loadUserlandModel(name,subdirs);if(M)_loaded[name]=M}}catch(err){console.error("[orm] deferred model load failed:",err)}finally{_modelsSettled=true;_readyResolve()}});export const Activity=lazyModel("Activity");export const AnalyticsEvent=lazyModel("AnalyticsEvent");export const Automation=lazyModel("Automation");export const AutomationRun=lazyModel("AutomationRun");export const Auction=lazyModel("Auction");export const CampaignVariant=lazyModel("CampaignVariant");export const CommunicationSuppression=lazyModel("CommunicationSuppression");export const ConsentEvent=lazyModel("ConsentEvent");export const SenderDomain=lazyModel("SenderDomain");export const UsageEvent=lazyModel("UsageEvent");export const AuctionItem=lazyModel("AuctionItem");export const Author=lazyModel("Author");export const Bid=lazyModel("Bid");export const Board=lazyModel("Board");export const BoardColumn=lazyModel("BoardColumn");export const Campaign=lazyModel("Campaign");export const Card=lazyModel("Card");export const CardAttachment=lazyModel("CardAttachment");export const CardComment=lazyModel("CardComment");export const Cart=lazyModel("Cart");export const CartItem=lazyModel("CartItem");export const Category=lazyModel("Category");export const Comment=lazyModel("Comment");export const Coupon=lazyModel("Coupon");export const Customer=lazyModel("Customer");export const DeliveryRoute=lazyModel("DeliveryRoute");export const DeliveryStop=lazyModel("DeliveryStop");export const Deployment=lazyModel("Deployment");export const FeedbackToken=lazyModel("FeedbackToken");export const DigitalDelivery=lazyModel("DigitalDelivery");export const Courier=lazyModel("Courier");export const CourierPing=lazyModel("CourierPing");export const CampaignSend=lazyModel("CampaignSend");export const EmailList=lazyModel("EmailList");export const EmailListSubscriber=lazyModel("EmailListSubscriber");export const Form=lazyModel("Form");export const FormField=lazyModel("FormField");export const FormSubmission=lazyModel("FormSubmission");export const MagicLinkToken=lazyModel("MagicLinkToken");export const Menu=lazyModel("Menu");export const MenuItem=lazyModel("MenuItem");export const PageRevision=lazyModel("PageRevision");export const Pledge=lazyModel("Pledge");export const Redirect=lazyModel("Redirect");export const Site=lazyModel("Site");export const SiteDomain=lazyModel("SiteDomain");export const SmsOptOut=lazyModel("SmsOptOut");export const GdprRequest=lazyModel("GdprRequest");export const StorageItem=lazyModel("StorageItem");export const StorageItemTask=lazyModel("StorageItemTask");export const EmailIdempotency=lazyModel("EmailIdempotency");export const EmailSuppression=lazyModel("EmailSuppression");export const EmailWebhookEvent=lazyModel("EmailWebhookEvent");export const ErrorModel=lazyModel("Error");export const GiftCard=lazyModel("GiftCard");export const Label=lazyModel("Label");export const LicenseActivation=lazyModel("LicenseActivation");export const LicenseKey=lazyModel("LicenseKey");export const LicenseSeat=lazyModel("LicenseSeat");export const Discount=lazyModel("Discount");export const PostPurchaseOffer=lazyModel("PostPurchaseOffer");export const PostPurchaseOfferResponse=lazyModel("PostPurchaseOfferResponse");export const Log=lazyModel("Log");export const LoyaltyPoint=lazyModel("LoyaltyPoint");export const LoyaltyReward=lazyModel("LoyaltyReward");export const MailPreference=lazyModel("MailPreference");export const Manufacturer=lazyModel("Manufacturer");export const Notification=lazyModel("Notification");export const NotificationDelivery=lazyModel("NotificationDelivery");export const Order=lazyModel("Order");export const OrderIdempotency=lazyModel("OrderIdempotency");export const PersonalAccessToken=lazyModel("PersonalAccessToken");export const OrderItem=lazyModel("OrderItem");export const Page=lazyModel("Page");export const Payment=lazyModel("Payment");export const PaymentWebhookEvent=lazyModel("PaymentWebhookEvent");export const PaymentMethod=lazyModel("PaymentMethod");export const PaymentProduct=lazyModel("PaymentProduct");export const PaymentTransaction=lazyModel("PaymentTransaction");export const Post=lazyModel("Post");export const Categorizable=lazyModel("Categorizable");export const PrintDevice=lazyModel("PrintDevice");export const Product=lazyModel("Product");export const ProductUnit=lazyModel("ProductUnit");export const ProductVariant=lazyModel("ProductVariant");export const QueryLog=lazyModel("QueryLog");export const Receipt=lazyModel("Receipt");export const Referral=lazyModel("Referral");export const ReferralCode=lazyModel("ReferralCode");export const Release=lazyModel("Release");export const Request=lazyModel("Request");export const Review=lazyModel("Review");export const ShippingMethod=lazyModel("ShippingMethod");export const ShippingRate=lazyModel("ShippingRate");export const ShippingZone=lazyModel("ShippingZone");export const SocialPost=lazyModel("SocialPost");export const SocialAccount=lazyModel("SocialAccount");export const Subscriber=lazyModel("Subscriber");export const SubscriberEmail=lazyModel("SubscriberEmail");export const Subscription=lazyModel("Subscription");export const Tag=lazyModel("Tag");export const TaxRate=lazyModel("TaxRate");export const Team=lazyModel("Team");export const TeamInvitation=lazyModel("TeamInvitation");export const TeamMember=lazyModel("TeamMember");export const Transaction=lazyModel("Transaction");export const WaitlistProduct=lazyModel("WaitlistProduct");export const WaitlistRestaurant=lazyModel("WaitlistRestaurant");export const Websocket=lazyModel("Websocket");const _allExports={User,Job,FailedJob,QueueWorker,Activity,AnalyticsEvent,Automation,AutomationRun,Auction,AuctionItem,Author,Bid,Board,BoardColumn,Campaign,CampaignSend,CampaignVariant,Card,CardComment,Cart,CartItem,Categorizable,Category,Comment,Coupon,Customer,Discount,CommunicationSuppression,ConsentEvent,DeliveryRoute,DeliveryStop,Deployment,DigitalDelivery,Courier,CourierPing,EmailList,EmailListSubscriber,EmailIdempotency,EmailSuppression,EmailWebhookEvent,ErrorModel,Form,FormField,FormSubmission,GdprRequest,GiftCard,Label,LicenseActivation,LicenseKey,LicenseSeat,Log,LoyaltyPoint,LoyaltyReward,MailPreference,Manufacturer,Notification,MagicLinkToken,Menu,MenuItem,NotificationDelivery,Order,OrderIdempotency,OrderItem,Page,PageRevision,Payment,PaymentMethod,PaymentProduct,PaymentTransaction,PaymentWebhookEvent,Pledge,Post,PostPurchaseOffer,PostPurchaseOfferResponse,PrintDevice,Product,ProductUnit,ProductVariant,QueryLog,Receipt,Release,Request,Review,ShippingMethod,Redirect,SenderDomain,ShippingRate,ShippingZone,Site,SiteDomain,SmsOptOut,SocialAccount,SocialPost,Subscriber,SubscriberEmail,Subscription,Tag,TaxRate,Team,TeamInvitation,TeamMember,Transaction,UsageEvent,WaitlistProduct,WaitlistRestaurant,Websocket};const g=globalThis;for(const[name,M]of Object.entries(_allExports)){if(M&&g[name]===undefined)g[name]=M}export const modelGlobalNames=Object.keys(_allExports);async function _safeAll(M){if(!M)return[];try{if(typeof M.all==="function"){const rows=await M.all();return Array.isArray(rows)?rows:[]}if(typeof M.get==="function"){const rows=await M.get();return Array.isArray(rows)?rows:[]}}catch{}return[]}function _safeGet(row,key,fallback=""){if(!row)return fallback;try{if(typeof row.get==="function"){const v=row.get(key);if(v!==undefined&&v!==null)return v}}catch{}const direct=row?.[key];return direct!==undefined&&direct!==null?direct:fallback}if(g.safeAll===undefined)g.safeAll=_safeAll;if(g.safeGet===undefined)g.safeGet=_safeGet;export*from"./messaging";
1
+ import"@stacksjs/validation/runtime";import{isCompiledBinary}from"@stacksjs/path";export*from"./utils/prunable";export{collectEncryptedAttributes,decryptRow,decryptRows,decryptValue,decryptValueInPlace,encryptedColumns,encryptRow,encryptValue,isEncrypted}from"./utils/encrypted";export{setAuditUser,createAuditMethods}from"./traits/audit";export{createCommentableMethods}from"./traits/commentable";export{createTaggableMethods}from"./traits/taggable";export{createCategorizableMethods}from"./traits/categorizable";export{createLikeableMethods}from"./traits/likeable";export{BILLABLE_INSTANCE_METHODS,isBillable,SubscriptionNotOwnedError}from"./traits/billable";export{filterFillable,getWritableFields,isUniqueViolation,mapWriteError,toSnakeCaseKeys}from"./auto-crud";export{customerOwnership,parentOwnership,selfOwnership,siteOwnership,teamMembershipOwnership}from"./ownership";export*from"./batch-loader";export*from"./db";export*from"./subquery";export*from"./transaction";export*from"./locked-row";export*from"./row-token";export*from"./gdpr";export*from"./model-types";export*from"./types";export*from"@stacksjs/model-meta";export*from"./define-model";export*from"./extend-model";export{buildDatabaseSchema,renderDatabaseTypeFile}from"./generate-database-schema";export{isCursorPaginator,isPaginator,isSimplePaginator,toCursorPaginator,toPaginator,toSimplePaginator}from"@stacksjs/pagination";export{enrichPaginatorUrls,parseCursor,resolveCursorArgs,resolvePageArgs}from"./paginator-request";async function importDefault(modulePath){for(let attempt=0;;attempt++){const mod=await import(modulePath);try{return mod.default}catch(err){if(attempt<5&&err instanceof ReferenceError&&/before initialization/.test(err.message)){await new Promise((resolve)=>setTimeout(resolve,0));continue}throw err}}}let announcedCompiledSkip=false;async function loadUserlandModel(modelName,subdirs=[""]){if(isCompiledBinary()){if(!announcedCompiledSkip){announcedCompiledSkip=true;console.debug("[orm] running from a compiled binary, so framework default models are not probed on disk; models this app uses are bundled.")}return null}const{path}=await import("@stacksjs/path");const userPath=path.userModelsPath(`${modelName}.ts`);try{if(await Bun.file(userPath).exists()){return await importDefault(userPath)}}catch(err){console.error(`[orm] Failed to import userland model ${modelName} from ${userPath} - falling back to framework default. Reason:`,err)}for(const sub of subdirs){const prefix=sub?`${sub}/`:"";const defaultPath=path.frameworkPath(`defaults/app/Models/${prefix}${modelName}.ts`);try{if(await Bun.file(defaultPath).exists()){return await importDefault(defaultPath)}}catch(err){console.error(`[orm] Failed to import framework default model ${modelName} from ${defaultPath} - trying next subdir. Reason:`,err)}}return null}const _loaded={};let _modelsSettled=false;const QUERY_ENTRYPOINTS=new Set(["where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","latest","oldest","limit","take","skip","select","find","findOrFail","findMany","first","firstOrFail","all","get","paginate","count","sum","avg","min","max","create","createMany","firstOrCreate","updateOrCreate","save","update","updateMany","delete","destroy","remove","truncate"]);function featureGateFor(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export function frameworkModelFeature(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export class ModelUnavailableError extends Error{model;feature;name="ModelUnavailableError";constructor(model,feature){super(`Model "${model}" is not available in this process. ${feature?`The '${feature}' feature is off, so this model was never loaded - set \`enabled: true\` in config/${feature}.ts to use it.`:`No model file for it was found under app/Models or the framework defaults.`}`);this.model=model;this.feature=feature}}function unavailableModel(name){return new ModelUnavailableError(name,featureGateFor(name))}let _readyResolve=()=>{};export const ormReady=new Promise((resolve)=>{_readyResolve=resolve});function lazyModel(name){return new Proxy(function _modelStub(){},{get(_target,prop){if(prop==="then")return;const m=_loaded[name];if(m==null){if(_modelsSettled&&typeof prop==="string"&&QUERY_ENTRYPOINTS.has(prop))throw unavailableModel(name);return}const value=m[prop];return typeof value==="function"?value.bind(m):value},set(_target,prop,value){const m=_loaded[name];if(m==null)return false;m[prop]=value;return true},has(_target,prop){const m=_loaded[name];return m==null?false:(prop in m)},apply(_target,thisArg,args){const m=_loaded[name];if(m==null||typeof m!=="function")return;return m.apply(thisArg,args)}})}export const User=lazyModel("User");export const Job=lazyModel("Job");export const QueueWorker=lazyModel("QueueWorker");export const FailedJob=lazyModel("FailedJob");const FRAMEWORK_MODEL_MANIFEST=[["QueueWorker",[""],"queue"],["Referral",[""],"auth"],["ReferralCode",[""],"auth"],["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["EmailList",[""],"auth"],["EmailListSubscriber",[""],"auth"],["Subscription",[""],"auth"],["Categorizable",["Content"],"cms"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["GdprRequest",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardAttachment",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["FeedbackToken",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["StorageItem",[""],"dashboard"],["StorageItemTask",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["Discount",["commerce"],"commerce"],["PostPurchaseOffer",["commerce"],"commerce"],["PostPurchaseOfferResponse",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["LicenseActivation",["commerce"],"commerce"],["LicenseSeat",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["PaymentWebhookEvent",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{const{feature}=await import("@stacksjs/config");const userModel=await loadUserlandModel("User");if(userModel)_loaded.User=userModel;if(feature("queue")){const job=await loadUserlandModel("Job");if(job)_loaded.Job=job;const failedJob=await loadUserlandModel("FailedJob");if(failedJob)_loaded.FailedJob=failedJob}for(const[name,subdirs,featureFlag]of FRAMEWORK_MODEL_MANIFEST){if(!feature(featureFlag))continue;const M=await loadUserlandModel(name,subdirs);if(M)_loaded[name]=M}}catch(err){console.error("[orm] deferred model load failed:",err)}finally{_modelsSettled=true;_readyResolve()}});export const Activity=lazyModel("Activity");export const AnalyticsEvent=lazyModel("AnalyticsEvent");export const Automation=lazyModel("Automation");export const AutomationRun=lazyModel("AutomationRun");export const Auction=lazyModel("Auction");export const CampaignVariant=lazyModel("CampaignVariant");export const CommunicationSuppression=lazyModel("CommunicationSuppression");export const ConsentEvent=lazyModel("ConsentEvent");export const SenderDomain=lazyModel("SenderDomain");export const UsageEvent=lazyModel("UsageEvent");export const AuctionItem=lazyModel("AuctionItem");export const Author=lazyModel("Author");export const Bid=lazyModel("Bid");export const Board=lazyModel("Board");export const BoardColumn=lazyModel("BoardColumn");export const Campaign=lazyModel("Campaign");export const Card=lazyModel("Card");export const CardAttachment=lazyModel("CardAttachment");export const CardComment=lazyModel("CardComment");export const Cart=lazyModel("Cart");export const CartItem=lazyModel("CartItem");export const Category=lazyModel("Category");export const Comment=lazyModel("Comment");export const Coupon=lazyModel("Coupon");export const Customer=lazyModel("Customer");export const DeliveryRoute=lazyModel("DeliveryRoute");export const DeliveryStop=lazyModel("DeliveryStop");export const Deployment=lazyModel("Deployment");export const FeedbackToken=lazyModel("FeedbackToken");export const DigitalDelivery=lazyModel("DigitalDelivery");export const Courier=lazyModel("Courier");export const CourierPing=lazyModel("CourierPing");export const CampaignSend=lazyModel("CampaignSend");export const EmailList=lazyModel("EmailList");export const EmailListSubscriber=lazyModel("EmailListSubscriber");export const Form=lazyModel("Form");export const FormField=lazyModel("FormField");export const FormSubmission=lazyModel("FormSubmission");export const MagicLinkToken=lazyModel("MagicLinkToken");export const Menu=lazyModel("Menu");export const MenuItem=lazyModel("MenuItem");export const PageRevision=lazyModel("PageRevision");export const Pledge=lazyModel("Pledge");export const Redirect=lazyModel("Redirect");export const Site=lazyModel("Site");export const SiteDomain=lazyModel("SiteDomain");export const SmsOptOut=lazyModel("SmsOptOut");export const GdprRequest=lazyModel("GdprRequest");export const StorageItem=lazyModel("StorageItem");export const StorageItemTask=lazyModel("StorageItemTask");export const EmailIdempotency=lazyModel("EmailIdempotency");export const EmailSuppression=lazyModel("EmailSuppression");export const EmailWebhookEvent=lazyModel("EmailWebhookEvent");export const ErrorModel=lazyModel("Error");export const GiftCard=lazyModel("GiftCard");export const Label=lazyModel("Label");export const LicenseActivation=lazyModel("LicenseActivation");export const LicenseKey=lazyModel("LicenseKey");export const LicenseSeat=lazyModel("LicenseSeat");export const Discount=lazyModel("Discount");export const PostPurchaseOffer=lazyModel("PostPurchaseOffer");export const PostPurchaseOfferResponse=lazyModel("PostPurchaseOfferResponse");export const Log=lazyModel("Log");export const LoyaltyPoint=lazyModel("LoyaltyPoint");export const LoyaltyReward=lazyModel("LoyaltyReward");export const MailPreference=lazyModel("MailPreference");export const Manufacturer=lazyModel("Manufacturer");export const Notification=lazyModel("Notification");export const NotificationDelivery=lazyModel("NotificationDelivery");export const Order=lazyModel("Order");export const OrderIdempotency=lazyModel("OrderIdempotency");export const PersonalAccessToken=lazyModel("PersonalAccessToken");export const OrderItem=lazyModel("OrderItem");export const Page=lazyModel("Page");export const Payment=lazyModel("Payment");export const PaymentWebhookEvent=lazyModel("PaymentWebhookEvent");export const PaymentMethod=lazyModel("PaymentMethod");export const PaymentProduct=lazyModel("PaymentProduct");export const PaymentTransaction=lazyModel("PaymentTransaction");export const Post=lazyModel("Post");export const Categorizable=lazyModel("Categorizable");export const PrintDevice=lazyModel("PrintDevice");export const Product=lazyModel("Product");export const ProductUnit=lazyModel("ProductUnit");export const ProductVariant=lazyModel("ProductVariant");export const QueryLog=lazyModel("QueryLog");export const Receipt=lazyModel("Receipt");export const Referral=lazyModel("Referral");export const ReferralCode=lazyModel("ReferralCode");export const Release=lazyModel("Release");export const Request=lazyModel("Request");export const Review=lazyModel("Review");export const ShippingMethod=lazyModel("ShippingMethod");export const ShippingRate=lazyModel("ShippingRate");export const ShippingZone=lazyModel("ShippingZone");export const SocialPost=lazyModel("SocialPost");export const SocialAccount=lazyModel("SocialAccount");export const Subscriber=lazyModel("Subscriber");export const SubscriberEmail=lazyModel("SubscriberEmail");export const Subscription=lazyModel("Subscription");export const Tag=lazyModel("Tag");export const TaxRate=lazyModel("TaxRate");export const Team=lazyModel("Team");export const TeamInvitation=lazyModel("TeamInvitation");export const TeamMember=lazyModel("TeamMember");export const Transaction=lazyModel("Transaction");export const WaitlistProduct=lazyModel("WaitlistProduct");export const WaitlistRestaurant=lazyModel("WaitlistRestaurant");export const Websocket=lazyModel("Websocket");const _allExports={User,Job,FailedJob,QueueWorker,Activity,AnalyticsEvent,Automation,AutomationRun,Auction,AuctionItem,Author,Bid,Board,BoardColumn,Campaign,CampaignSend,CampaignVariant,Card,CardComment,Cart,CartItem,Categorizable,Category,Comment,Coupon,Customer,Discount,CommunicationSuppression,ConsentEvent,DeliveryRoute,DeliveryStop,Deployment,DigitalDelivery,Courier,CourierPing,EmailList,EmailListSubscriber,EmailIdempotency,EmailSuppression,EmailWebhookEvent,ErrorModel,Form,FormField,FormSubmission,GdprRequest,GiftCard,Label,LicenseActivation,LicenseKey,LicenseSeat,Log,LoyaltyPoint,LoyaltyReward,MailPreference,Manufacturer,Notification,MagicLinkToken,Menu,MenuItem,NotificationDelivery,Order,OrderIdempotency,OrderItem,Page,PageRevision,Payment,PaymentMethod,PaymentProduct,PaymentTransaction,PaymentWebhookEvent,Pledge,Post,PostPurchaseOffer,PostPurchaseOfferResponse,PrintDevice,Product,ProductUnit,ProductVariant,QueryLog,Receipt,Release,Request,Review,ShippingMethod,Redirect,SenderDomain,ShippingRate,ShippingZone,Site,SiteDomain,SmsOptOut,SocialAccount,SocialPost,Subscriber,SubscriberEmail,Subscription,Tag,TaxRate,Team,TeamInvitation,TeamMember,Transaction,UsageEvent,WaitlistProduct,WaitlistRestaurant,Websocket};const g=globalThis;for(const[name,M]of Object.entries(_allExports)){if(M&&g[name]===undefined)g[name]=M}export const modelGlobalNames=Object.keys(_allExports);async function _safeAll(M){if(!M)return[];try{if(typeof M.all==="function"){const rows=await M.all();return Array.isArray(rows)?rows:[]}if(typeof M.get==="function"){const rows=await M.get();return Array.isArray(rows)?rows:[]}}catch{}return[]}function _safeGet(row,key,fallback=""){if(!row)return fallback;try{if(typeof row.get==="function"){const v=row.get(key);if(v!==undefined&&v!==null)return v}}catch{}const direct=row?.[key];return direct!==undefined&&direct!==null?direct:fallback}if(g.safeAll===undefined)g.safeAll=_safeAll;if(g.safeGet===undefined)g.safeGet=_safeGet;export*from"./messaging";
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/orm",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.685",
5
+ "version": "0.75.690",
6
6
  "description": "The Stacks ORM integration",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -63,32 +63,32 @@
63
63
  "prepublishOnly": "bun run build"
64
64
  },
65
65
  "dependencies": {
66
- "@stacksjs/cache": "0.75.685",
67
- "@stacksjs/cli": "0.75.685",
68
- "@stacksjs/config": "0.75.685",
69
- "@stacksjs/database": "0.75.685",
70
- "@stacksjs/env": "0.75.685",
71
- "@stacksjs/error-handling": "0.75.685",
72
- "@stacksjs/events": "0.75.685",
73
- "@stacksjs/logging": "0.75.685",
74
- "@stacksjs/model-meta": "0.75.685",
75
- "@stacksjs/pagination": "0.75.685",
76
- "@stacksjs/path": "0.75.685",
77
- "@stacksjs/query-builder": "0.75.685",
78
- "@stacksjs/realtime": "0.75.685",
79
- "@stacksjs/router": "0.75.685",
80
- "@stacksjs/storage": "0.75.685",
81
- "@stacksjs/strings": "0.75.685",
66
+ "@stacksjs/cache": "0.75.690",
67
+ "@stacksjs/cli": "0.75.690",
68
+ "@stacksjs/config": "0.75.690",
69
+ "@stacksjs/database": "0.75.690",
70
+ "@stacksjs/env": "0.75.690",
71
+ "@stacksjs/error-handling": "0.75.690",
72
+ "@stacksjs/events": "0.75.690",
73
+ "@stacksjs/logging": "0.75.690",
74
+ "@stacksjs/model-meta": "0.75.690",
75
+ "@stacksjs/pagination": "0.75.690",
76
+ "@stacksjs/path": "0.75.690",
77
+ "@stacksjs/query-builder": "0.75.690",
78
+ "@stacksjs/realtime": "0.75.690",
79
+ "@stacksjs/router": "0.75.690",
80
+ "@stacksjs/storage": "0.75.690",
81
+ "@stacksjs/strings": "0.75.690",
82
82
  "@stacksjs/ts-validation": "^0.5.7",
83
- "@stacksjs/validation": "0.75.685",
83
+ "@stacksjs/validation": "0.75.690",
84
84
  "bun-query-builder": "^0.6.4",
85
85
  "stripe": "23.0.0"
86
86
  },
87
87
  "peerDependencies": {
88
- "@stacksjs/auth": "0.75.685",
89
- "@stacksjs/payments": "0.75.685",
90
- "@stacksjs/queue": "0.75.685",
91
- "@stacksjs/search-engine": "0.75.685"
88
+ "@stacksjs/auth": "0.75.690",
89
+ "@stacksjs/payments": "0.75.690",
90
+ "@stacksjs/queue": "0.75.690",
91
+ "@stacksjs/search-engine": "0.75.690"
92
92
  },
93
93
  "peerDependenciesMeta": {
94
94
  "@stacksjs/auth": {
@@ -102,7 +102,7 @@
102
102
  }
103
103
  },
104
104
  "devDependencies": {
105
- "@stacksjs/types": "0.75.685",
105
+ "@stacksjs/types": "0.75.690",
106
106
  "better-dx": "^0.2.39"
107
107
  }
108
108
  }