@stacksjs/api 0.72.56 → 0.72.60

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.
Files changed (2) hide show
  1. package/dist/index.js +21 -21
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,43 +1,43 @@
1
1
  // @bun
2
- var NJ=Object.defineProperty;var HJ=($)=>$;function AJ($,J){this[$]=HJ.bind(null,J)}var Q$=($,J)=>{for(var O in J)NJ($,O,{get:J[O],enumerable:!0,configurable:!0,set:AJ.bind(J,O)})};var d=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var f$={};Q$(f$,{schemaType:()=>c,renderOpenApiTypes:()=>IJ});function UJ($){return typeof $==="string"?JSON.stringify($):String($)}function c($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(UJ).join(" | ");if($.type==="string")return"string";if($.type==="number"||$.type==="integer")return"number";if($.type==="boolean")return"boolean";if($.type==="null")return"null";if($.type==="array")return`Array<${c($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let J=new Set($.required||[]),O=Object.entries($.properties||{}).map(([G,Z])=>`${JSON.stringify(G)}${J.has(G)?"":"?"}: ${c(Z)}`);if($.additionalProperties){let G=$.additionalProperties===!0?"unknown":c($.additionalProperties);O.push(`[key: string]: ${G}`)}return O.length?`{ ${O.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function EJ($=[]){return` parameters: {
3
- ${["query","header","path","cookie"].map((O)=>{let G=$.filter((z)=>z.in===O);if(!G.length)return` ${O}?: never`;let Z=G.map((z)=>`${JSON.stringify(z.name)}${z.required?"":"?"}: ${c(z.schema)}`);return` ${O}${G.every((z)=>!z.required)?"?":""}: { ${Z.join("; ")} }`}).join(`
2
+ var bt=Object.defineProperty;var wt=(e)=>e;function Rt(e,t){this[e]=wt.bind(null,t)}var ae=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Rt.bind(t,n)})};var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=import.meta.require;var De={};ae(De,{renderOpenApiTypes:()=>At,schemaType:()=>M});function St(e){return typeof e==="string"?JSON.stringify(e):String(e)}function M(e){if(!e)return"unknown";if(e.enum?.length)return e.enum.map(St).join(" | ");if(e.type==="string")return"string";if(e.type==="number"||e.type==="integer")return"number";if(e.type==="boolean")return"boolean";if(e.type==="null")return"null";if(e.type==="array")return`Array<${M(e.items)}>`;if(e.type==="object"||e.properties||e.additionalProperties){let t=new Set(e.required||[]),n=Object.entries(e.properties||{}).map(([r,s])=>`${JSON.stringify(r)}${t.has(r)?"":"?"}: ${M(s)}`);if(e.additionalProperties){let r=e.additionalProperties===!0?"unknown":M(e.additionalProperties);n.push(`[key: string]: ${r}`)}return n.length?`{ ${n.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function kt(e=[]){return` parameters: {
3
+ ${["query","header","path","cookie"].map((n)=>{let r=e.filter((o)=>o.in===n);if(!r.length)return` ${n}?: never`;let s=r.map((o)=>`${JSON.stringify(o.name)}${o.required?"":"?"}: ${M(o.schema)}`);return` ${n}${r.every((o)=>!o.required)?"?":""}: { ${s.join("; ")} }`}).join(`
4
4
  `)}
5
- }`}function P$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([J,O])=>`${JSON.stringify(J)}: ${c(O.schema)}`).join("; ")} }`}function SJ($){let J=$.requestBody?`
6
- requestBody${$.requestBody.required?"":"?"}: { content: ${P$($.requestBody.content)} }`:`
7
- requestBody?: never`,O=Object.entries($.responses||{}).map(([G,Z])=>` ${JSON.stringify(G)}: { content: ${P$(Z.content)} }`);return`{
8
- ${EJ($.parameters)}${J}
5
+ }`}function qe(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${M(n.schema)}`).join("; ")} }`}function $t(e){let t=e.requestBody?`
6
+ requestBody${e.requestBody.required?"":"?"}: { content: ${qe(e.requestBody.content)} }`:`
7
+ requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${qe(s.content)} }`);return`{
8
+ ${kt(e.parameters)}${t}
9
9
  responses: {
10
- ${O.join(`
10
+ ${n.join(`
11
11
  `)}
12
12
  }
13
- }`}function IJ($){let J=Object.entries($.paths||{}).map(([G,Z])=>{let z=DJ.map((Q)=>{let W=Z[Q];return W?` ${Q}: ${SJ(W)}`:` ${Q}?: never`});return` ${JSON.stringify(G)}: {
14
- ${z.join(`
13
+ }`}function At(e){let t=Object.entries(e.paths||{}).map(([r,s])=>{let o=Ot.map((i)=>{let c=s[i];return c?` ${i}: ${$t(c)}`:` ${i}?: never`});return` ${JSON.stringify(r)}: {
14
+ ${o.join(`
15
15
  `)}
16
- }`}),O=Object.entries($.components?.schemas||{}).map(([G,Z])=>` ${JSON.stringify(G)}: ${c(Z)}`);return`/**
16
+ }`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${M(s)}`);return`/**
17
17
  * Generated from storage/framework/api/openapi.json by @stacksjs/api.
18
18
  * Do not edit this file directly; run bun run docs:artifacts to regenerate it.
19
19
  */
20
20
 
21
21
  export interface paths {
22
- ${J.join(`
22
+ ${t.join(`
23
23
  `)}
24
24
  }
25
25
 
26
26
  export interface components {
27
27
  schemas: {
28
- ${O.join(`
28
+ ${n.join(`
29
29
  `)}
30
30
  }
31
31
  }
32
- `}var DJ;var L$=d(()=>{DJ=["get","put","post","delete","options","head","patch","trace"]});var g$={};Q$(g$,{renderApiClient:()=>RJ,methodName:()=>b$});function b$($){let J=$.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),O=J[0]?.toLowerCase()==="api"?J.slice(1):J[1]?.toLowerCase()==="api"?[J[0],...J.slice(2)]:J,[G,...Z]=O;if(!G)return"call";let z=G.charAt(0).toLowerCase()+G.slice(1),Q=Z.map((x)=>x.charAt(0).toUpperCase()+x.slice(1)),W=[z,...Q].join("");return/^[a-z_$]/i.test(W)?W:`call${W.charAt(0).toUpperCase()}${W.slice(1)}`}function VJ($){let J=$.responses??{},O=Object.keys(J).find((z)=>z.startsWith("2"));if(!O)return"unknown";let G=J[O]?.content,Z=G?.["application/json"]??Object.values(G??{})[0];return Z?.schema?c(Z.schema):"unknown"}function MJ($,J=" "){let O=$.filter(Boolean);if(!O.length)return"";return`${J}/**
33
- ${O.map((G)=>`${J} * ${G}`).join(`
32
+ `}var Ot;var ce=Z(()=>{Ot=["get","put","post","delete","options","head","patch","trace"]});var Ce={};ae(Ce,{methodName:()=>Ne,renderApiClient:()=>_t});function Ne(e){let t=e.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),n=t[0]?.toLowerCase()==="api"?t.slice(1):t[1]?.toLowerCase()==="api"?[t[0],...t.slice(2)]:t,[r,...s]=n;if(!r)return"call";let o=r.charAt(0).toLowerCase()+r.slice(1),i=s.map((p)=>p.charAt(0).toUpperCase()+p.slice(1)),c=[o,...i].join("");return/^[a-z_$]/i.test(c)?c:`call${c.charAt(0).toUpperCase()}${c.slice(1)}`}function jt(e){let t=e.responses??{},n=Object.keys(t).find((o)=>o.startsWith("2"));if(!n)return"unknown";let r=t[n]?.content,s=r?.["application/json"]??Object.values(r??{})[0];return s?.schema?M(s.schema):"unknown"}function xt(e,t=" "){let n=e.filter(Boolean);if(!n.length)return"";return`${t}/**
33
+ ${n.map((r)=>`${t} * ${r}`).join(`
34
34
  `)}
35
- ${J} */
36
- `}function CJ($,J,O,G){let Z=O.parameters??[],z=Z.filter((E)=>E.in==="path"),Q=Z.filter((E)=>E.in==="query"),W=O.requestBody?.content?.["application/json"]?.schema,x=Boolean(O.requestBody?.required),X=[];for(let E of[...z,...Q]){let k=E.in==="path"||E.required;X.push(`${JSON.stringify(E.name)}${k?"":"?"}: ${c(E.schema)}`)}if(W)X.push(`body${x?"":"?"}: ${c(W)}`);let K=[...z,...Q].every((E)=>E.in!=="path"&&!E.required)&&(!W||!x),B=X.length?`input${K?"?":""}: { ${X.join("; ")} }, `:"",D=Q.length?`[${Q.map((E)=>JSON.stringify(E.name)).join(", ")}]`:"[]";return`${MJ([O.summary&&O.summary!==$?O.summary:`${J.toUpperCase()} ${$}`,O.description??""])} ${G}(${B}options?: RequestOptions): Promise<ApiResult<${VJ(O)}>> {
37
- return request(config, ${JSON.stringify(J.toUpperCase())}, ${JSON.stringify($)}, ${X.length?"input ?? {}":"{}"}, ${D}, ${W?"true":"false"}, options)
38
- },`}function RJ($,J={}){let O=J.name??"API",G=new Map,Z=[];for(let[z,Q]of Object.entries($.paths??{}))for(let W of FJ){let x=Q[W];if(!x)continue;let X=b$(x.operationId??`${W}_${z}`),K=G.get(X)??0;G.set(X,K+1),Z.push(CJ(z,W,x,K===0?X:`${X}${K+1}`))}return`/* eslint-disable */
35
+ ${t} */
36
+ `}function Pt(e,t,n,r){let s=n.parameters??[],o=s.filter((S)=>S.in==="path"),i=s.filter((S)=>S.in==="query"),c=n.requestBody?.content?.["application/json"]?.schema,p=Boolean(n.requestBody?.required),d=[];for(let S of[...o,...i]){let v=S.in==="path"||S.required;d.push(`${JSON.stringify(S.name)}${v?"":"?"}: ${M(S.schema)}`)}if(c)d.push(`body${p?"":"?"}: ${M(c)}`);let u=[...o,...i].every((S)=>S.in!=="path"&&!S.required)&&(!c||!p),f=d.length?`input${u?"?":""}: { ${d.join("; ")} }, `:"",R=i.length?`[${i.map((S)=>JSON.stringify(S.name)).join(", ")}]`:"[]";return`${xt([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${f}options?: RequestOptions): Promise<ApiResult<${jt(n)}>> {
37
+ return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${d.length?"input ?? {}":"{}"}, ${R}, ${c?"true":"false"}, options)
38
+ },`}function _t(e,t={}){let n=t.name??"API",r=new Map,s=[];for(let[o,i]of Object.entries(e.paths??{}))for(let c of Tt){let p=i[c];if(!p)continue;let d=Ne(p.operationId??`${c}_${o}`),u=r.get(d)??0;r.set(d,u+1),s.push(Pt(o,c,p,u===0?d:`${d}${u+1}`))}return`/* eslint-disable */
39
39
  /**
40
- * ${O} client, generated from the OpenAPI document.
40
+ * ${n} client, generated from the OpenAPI document.
41
41
  *
42
42
  * Do not edit. Run \`buddy generate:openapi\` to rebuild it from the routes.
43
43
  *
@@ -129,11 +129,11 @@ export function createClient(config: ClientConfig) {
129
129
  /** The configuration in use, so a caller can rebuild a variant of it. */
130
130
  config,
131
131
 
132
- ${Z.join(`
132
+ ${s.join(`
133
133
 
134
134
  `)}
135
135
  }
136
136
  }
137
137
 
138
138
  export type Client = ReturnType<typeof createClient>
139
- `}var FJ;var B$=d(()=>{L$();FJ=["get","put","post","delete","options","head","patch"]});function kJ($){let J=$;return J?.code==="SQLITE_CONSTRAINT_UNIQUE"||J?.code==="SQLITE_CONSTRAINT"||J?.code==="23505"||J?.errno===1062||/unique|duplicate/i.test(J?.message??"")}function _$($,J,O){let G=$;if($ instanceof Error&&typeof G.status==="number"&&Number.isInteger(G.status)&&G.status>=400&&G.status<600){let Z={error:$.message};if(G.details!==void 0)Z.details=G.details;return{status:G.status,body:Z}}if(kJ($))return{status:409,body:{error:`${J} already exists`}};return{status:500,body:{error:`Failed to ${O} ${J}`,detail:String($)}}}function F($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function j$($){let J={};for(let[O,G]of Object.entries($))J[F(O)]=G;return J}function q$($,J){let O=String(J||"").replace(/^\/+|\/+$/g,""),G=String($).replace(/^\/+/,"");return`/api/${O?`${O}/`:""}${G}`}function w$($){if(!$)return null;let J=$.attributes??{};if(Object.prototype.hasOwnProperty.call(J,"teamId")||Object.prototype.hasOwnProperty.call(J,"team_id"))return"team_id";return $.belongsTo?.some((O)=>O==="Team")?"team_id":null}function c$($,J,O){let G=Object.keys($).find((z)=>F(z)===F(J));if(Array.isArray(O)){if(G===void 0)return{data:$,error:"Ownership value is required"};if(!O.some((z)=>String(z)===String($[G])))return{data:$,error:"Ownership value is not available to this caller"};return{data:{...$,[J]:$[G]}}}if(O===null||O===void 0)return{data:$,error:"Caller has no ownership identity"};let Z={...$};for(let z of Object.keys(Z))if(F(z)===F(J))delete Z[z];return Z[J]=O,{data:Z}}function v$($){if(!$)return[];let J=Object.entries($.attributes??{}).filter(([,O])=>O?.fillable===!0).map(([O])=>O);for(let O of $.belongsTo??[]){if(typeof O!=="string"||!O.trim())continue;let G=F(O.trim()).split("_").filter(Boolean);if(G.length===0)continue;let Z=`${G[0]}${G.slice(1).map((z)=>`${z[0]?.toUpperCase()}${z.slice(1)}`).join("")}Id`;J.push(Z)}return[...new Set(J)]}function N$($,J){if(!$||J.length===0)return{};let O={};for(let G of J){if(G in $){O[G]=$[G];continue}let Z=F(G);if(Z!==G&&Z in $)O[G]=$[Z]}return O}function PJ($,J){if($?.name!=="date"||J instanceof Date||typeof J!=="string")return J;let O=/^(\d{4})-(\d{2})-(\d{2})$/.exec(J);if(!O)return J;let G=Number(O[1]),Z=Number(O[2]),z=Number(O[3]),Q=new Date(Date.UTC(G,Z-1,z));if(Q.getUTCFullYear()!==G||Q.getUTCMonth()!==Z-1||Q.getUTCDate()!==z)return J;return Q}function H$($,J){if(!J.length)return $;let O={...$};for(let G of J)delete O[G],delete O[F(G)];return O}function r($,J){if(!$||J.length===0)return $;let O={...$};for(let G of J)delete O[G],delete O[F(G)];return O}function h$($,J){let O=new Map;for(let G of[...Object.keys($??{}),...fJ]){let Z=F(G);if(!/^\w+$/.test(Z))continue;O.set(G,Z),O.set(Z,Z)}for(let G of J)O.delete(G),O.delete(F(G));return O}function p$($,J,O){if(!J)return $;let G=String(J).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of G){let Q=z.startsWith("-"),W=Q?z.slice(1):z;if(!/^\w+$/.test(W))continue;let x=O.get(W);if(!x)continue;Z=Z.orderBy(x,Q?"desc":"asc")}return Z}function gJ($){try{return JSON.parse($)}catch{return $}}function yJ($){try{return JSON.parse($)}catch{return[]}}function A$($,J,O){if(!$||typeof $!=="object"||!J||Object.keys(J).length===0)return $;let G={...$};for(let[Z,z]of Object.entries(J)){let Q=typeof z==="string"?bJ[z]:z;if(!Q||typeof Q[O]!=="function")continue;if(Object.prototype.hasOwnProperty.call(G,Z))G[Z]=Q[O](G[Z]);let W=F(Z);if(W!==Z&&Object.prototype.hasOwnProperty.call(G,W))G[W]=Q[O](G[W])}return G}function D$($,J,O){let G=J?.attributes??{},Z={};for(let[z,Q]of Object.entries(G)){let W=Q?.validation?.rule;if(!W||typeof W.validate!=="function")continue;let x=Object.prototype.hasOwnProperty.call($,z);if(!x&&O==="updating")continue;let X=Q!==null&&typeof Q==="object"&&Object.prototype.hasOwnProperty.call(Q,"default"),K=x?$[z]:X?Q.default:void 0,B=PJ(W,K),D=W.validate(B);if(!D?.valid&&Array.isArray(D?.errors)&&D.errors.length>0)Z[z]=D.errors.map((C)=>Q?.validation?.message?.[C?.code]??C?.message??"invalid")}return Object.keys(Z).length===0?{valid:!0}:{valid:!1,errors:Z}}function U$($){return $.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function T$($){if(Array.isArray($))return $.filter((J)=>typeof J==="string"&&J.length>0);return typeof $==="string"&&$?[$]:[]}function m$($){let J=typeof $==="object"&&$!==null&&"middleware"in $,O=$?.middleware;if(!J)return{read:["auth"],write:["auth"],declared:!1};if(O&&typeof O==="object"&&!Array.isArray(O)){let Z=O;return{read:"read"in Z?T$(Z.read):["auth"],write:"write"in Z?T$(Z.write):["auth"],declared:!0}}let G=T$(O);return{read:G,write:G,declared:!0}}function i$($){let J=Number.parseInt($.get("page")||String(1),10),O=Number.isFinite(J)?Math.max(1,J):1,G=Number.parseInt($.get("per_page")||String(y$),10),Z=Math.min(Number.isFinite(G)?Math.max(1,G):y$,qJ);return{page:O,perPage:Z,offset:(O-1)*Z}}function W$($,J){let O=new URL($.toString());return O.searchParams.set("page",String(J)),`${O.pathname}${O.search}`}function K$($,J,O,G,Z,z){let Q=(J-1)*O,W=G===0,x={page:J,per_page:O,from:W?null:Q+1,to:W?null:Q+G,has_more_pages:Z,prev_page_url:J>1?W$($,J-1):null,next_page_url:Z?W$($,J+1):null};if(z!==void 0&&!Number.isNaN(z)){let X=Math.max(1,Math.ceil(z/O));x.total=z,x.last_page=X,x.first_page_url=W$($,1),x.last_page_url=W$($,X)}return x}function E$($,J,O,G,Z,z){let{page:Q,...W}=K$($,J,O,G,Z,z);return{current_page:Q,...W}}var fJ,bJ,y$=15,qJ=100;var n$=d(()=>{fJ=["id","uuid","created_at","updated_at","deleted_at"];bJ={string:{get:($)=>$!=null?String($):null,set:($)=>$!=null?String($):null},number:{get:($)=>$!=null?Number($):null,set:($)=>$!=null?Number($):null},integer:{get:($)=>$!=null?Math.trunc(Number($)):null,set:($)=>$!=null?Math.trunc(Number($)):null},float:{get:($)=>$!=null?Number.parseFloat(String($)):null,set:($)=>$!=null?Number.parseFloat(String($)):null},boolean:{get:($)=>$===1||$==="1"||$===!0||$==="true",set:($)=>$===!0||$===1||$==="1"||$==="true"?1:0},json:{get:($)=>$==null?null:typeof $==="string"?gJ($):$,set:($)=>$==null?null:typeof $==="string"?$:JSON.stringify($)},datetime:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString():$},date:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString().split("T")[0]:$},array:{get:($)=>$==null?[]:Array.isArray($)?$:typeof $==="string"?yJ($):[],set:($)=>$==null?null:Array.isArray($)?JSON.stringify($):$}}});var t$={};Q$(t$,{modelFiles:()=>o$,loadModelRegistry:()=>S$});import{readdirSync as wJ}from"fs";import{basename as cJ,extname as l$,join as vJ}from"path";function o$($){let J=[],O=(G)=>{let Z;try{Z=wJ(G,{withFileTypes:!0})}catch{return}for(let z of Z){let Q=vJ(G,z.name);if(z.isDirectory()){O(Q);continue}if(![".ts",".js"].includes(l$(z.name)))continue;if(z.name.startsWith(".")||z.name.startsWith("index"))continue;J.push(Q)}};return O($),J.sort()}async function u$($,J,O){for(let G of o$($))try{let Z=l$(G),z=await import(`${G}?t=${Date.now()}`),Q=z.default??z,W=Q.name??cJ(G,Z);J[W]={...Q,name:W}}catch(Z){O?.(G,Z)}}async function S$($){let J={};return await u$($.defaultsRoot,J,$.onImportError),await u$($.userRoot,J,$.onImportError),J}var I$=()=>{};import{route as i}from"@stacksjs/router";import{env as o}from"@stacksjs/env";import{projectPath as OJ,storagePath as hJ}from"@stacksjs/path";import{createQueryBuilder as pJ,defaultConfig as s$,setConfig as d$}from"@stacksjs/query-builder";import{HttpError as u}from"@stacksjs/error-handling";import{log as x$}from"@stacksjs/logging";function t($,J){let O=U$(J);return i.routes.some((G)=>G.method===$&&U$(String(G.path??""))===O)}function GJ($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([J,O])=>O.hidden===!0).map(([J])=>J)}function r$($){if($.endsWith("y")&&!/[aeiou]y$/i.test($))return`${$.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test($))return`${$}es`;return`${$}s`}async function a$($,J,O,G){if(!$.length)return $;let Z=O.split(",").map((X)=>X.trim()).filter(Boolean);if(!Z.length)return $;let z=Array.isArray(J.belongsTo)?J.belongsTo:[],Q=Array.isArray(J.hasMany)?J.hasMany:[],W=Array.isArray(J.hasOne)?J.hasOne:[],x=new Map;for(let X of z)x.set(F(X),{kind:"belongsTo",modelName:X});for(let X of W)x.set(F(X),{kind:"hasOne",modelName:X});for(let X of Q)x.set(r$(F(X)),{kind:"hasMany",modelName:X});for(let X of Z){let K=x.get(X);if(!K)continue;let B=G[K.modelName];if(!B)continue;let D=B.table||r$(F(K.modelName)),C=GJ(B),E=(k)=>r(G$(k,B),C);if(K.kind==="belongsTo"||K.kind==="hasOne"){let k=`${F(K.modelName)}_id`,V=[...new Set($.map((M)=>M[k]).filter((M)=>M!=null))];if(!V.length){for(let M of $)M[X]=null;continue}let q=await g.selectFrom(D).whereIn("id",V).get(),P=new Map;for(let M of q??[])P.set(String(M.id),E(M));for(let M of $)M[X]=P.get(String(M[k]))??null}else{let k=String(J.name??""),V=`${F(k)}_id`,q=[...new Set($.map((_)=>_.id).filter((_)=>_!=null))];if(!q.length){for(let _ of $)_[X]=[];continue}let P=await g.selectFrom(D).whereIn(V,q).get(),M=new Map;for(let _ of P??[]){let L=String(_[V]),Y=M.get(L)??[];Y.push(E(_)),M.set(L,Y)}for(let _ of $)_[X]=M.get(String(_.id))??[]}}return $}async function e$($,J){let O=J?.set;if(!O||typeof O!=="object")return $;let G={...$};for(let[Z,z]of Object.entries(O)){if(typeof z!=="function"||!(Z in G))continue;try{G[Z]=await z(G)}catch{}}return G}function $J($,J){return A$($,J?.casts,"set")}function G$($,J){return A$($,J?.casts,"get")}function j($,J=200){return new Response(JSON.stringify($),{status:J,headers:{"Content-Type":"application/json"}})}async function V$($){if(Number($.headers?.get?.("content-length")??0)>X$)throw new u(413,`Request body exceeds ${X$}-byte limit`);if($.jsonBody&&typeof $.jsonBody==="object")return $.jsonBody;if($.formBody&&typeof $.formBody==="object")return $.formBody;try{let O=await $.clone().text();if(O.length>X$)throw new u(413,`Request body exceeds ${X$}-byte limit`);if(!O)return{};let G=JSON.parse(O);return G&&typeof G==="object"&&!Array.isArray(G)?G:{}}catch(O){if(O instanceof u)throw O;throw new u(400,`Invalid JSON body: ${O.message}`)}}function Y$($){if($==null)return null;if(typeof $==="number")return Number.isFinite($)&&$>0?$:null;if(typeof $==="string"){let J=$.trim();if(!J)return null;if(/^\d+$/.test(J)){let O=Number(J);return Number.isFinite(O)&&O>0?O:null}return J}return null}function ZJ($){let J=$.bearerToken;if(typeof J==="function"){let G=J.call($);if(G)return G}let O=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof O==="string"&&O.startsWith("Bearer "))return O.substring(7);return null}async function a($){let J=$._authenticatedUser;if(J)return J;let O=ZJ($);if(!O)return null;try{let{Auth:G}=await import("@stacksjs/auth"),Z=await G.getUserFromToken(O);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function O$($,J){if($==null||J==null)return!1;if(Array.isArray(J))return J.some((O)=>String(O)===String($));return String($)===String(J)}function iJ($){let J=ZJ($),O=$.headers?.get?.("cookie")||"";return{bearerToken:()=>J,cookies:{get:(G)=>{for(let Z of O.split(";")){let z=Z.indexOf("=");if(z===-1)continue;if(Z.slice(0,z).trim()===G)return decodeURIComponent(Z.slice(z+1).trim())}return null}}}}function zJ($){if($?.ownership)return $.ownership;let J=w$($);if(!J)return null;return{field:J,resolve:async(O,G)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(iJ(G))}}}async function e($,J,O){let G=zJ($);if(!G||!G.field||typeof G.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof G.bypass==="function"?!!G.bypass(J,O):!1,z=null;try{z=await G.resolve(J,O)}catch{z=null}return{enforced:!0,value:z,field:String(G.field),bypass:Z}}async function JJ($,J,O,G){let Z=$?.authedFill?.[J];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(O,G);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[Q,W]of Object.entries(Z))try{z[Q]=typeof W==="function"?await W(O,G):W}catch{}return z}return{}}var mJ,F$,g,X$=1048576,QJ;var LJ=d(async()=>{n$();I$();mJ=OJ("config/qb.ts");try{let $=(await import(mJ)).default;d$($??s$)}catch{x$.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let $=o.DB_CONNECTION||"sqlite";d$({...s$,dialect:$,database:$==="sqlite"?{database:o.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:o.DB_DATABASE||"stacks",host:o.DB_HOST||"127.0.0.1",port:o.DB_PORT||($==="postgres"?5432:3306),username:o.DB_USERNAME||($==="postgres"?"postgres":"root"),password:o.DB_PASSWORD||""}})}F$=await S$({defaultsRoot:hJ("framework/defaults/app/Models"),userRoot:OJ("app/Models"),onImportError:($,J)=>x$.warn(`[orm] Could not load model ${$}: ${J.message}`)}),g=pJ();for(let[$,J]of Object.entries(F$)){let O=J.traits?.useApi;if(!O)continue;let G=typeof O==="object"?O:{},Z=G.uri||J.table||$.toLowerCase()+"s",z=G.routes||["index","show","store","update","destroy"],Q=J.table||Z,W=v$(J),x=GJ(J),X=q$(Z,G.prefix),K=h$(J.attributes,x),{read:B,write:D,declared:C}=m$(O);if(["store","update","destroy"].some((_)=>z.includes(_))&&C&&D.length===0)x$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${X} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((_)=>z.includes(_))&&C&&B.length===0)x$.debug(`[orm] ${$}: registering public read routes at ${X} (declared \`middleware.read: []\`)`);let V=!!zJ(J),q=V&&!B.includes("auth")?["auth",...B]:B,P=(_,L=q)=>{let Y=_;for(let T of L)if(Y&&typeof Y.middleware==="function")Y=Y.middleware(T);return Y};if(z.includes("index")&&!t("GET",X))P(i.get(X,async(_)=>{try{let L=new URL(_.url),{page:Y,perPage:T,offset:H}=i$(L.searchParams),N=L.searchParams.get("sort"),A=g.selectFrom(Q);A=p$(A,N,K);let w=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[f,b]of L.searchParams.entries()){if(w.has(f)||!b)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(f))continue;let l=K.get(f);if(l)A=A.where(l,"=",b)}let I=L.searchParams.get("search");if(I&&W.length>0){let f=W.slice(0,5);A=A.where((b)=>{for(let l of f)b=b.orWhere(F(l),"like",`%${I}%`);return b})}let R=L.searchParams.get("fields");if(R){let f=R.split(",").map((b)=>b.trim()).filter((b)=>/^[a-z_][a-z0-9_]*$/i.test(b)).map((b)=>F(b));if(f.length>0)A=A.select(f)}let y=!!J.traits?.useSoftDeletes,S=L.searchParams.get("withTrashed")==="true",h=L.searchParams.get("onlyTrashed")==="true";if(y&&!S)A=h?A.whereNotNull("deleted_at"):A.whereNull("deleted_at");let U=V?await e(J,await a(_),_):{enforced:!1,value:null,field:"",bypass:!1};if(U.enforced&&!U.bypass){if(U.value==null||Array.isArray(U.value)&&U.value.length===0){let f=E$(L,Y,T,0,!1,void 0);return new Response(JSON.stringify({data:[],...f,meta:K$(L,Y,T,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}A=Array.isArray(U.value)?A.where(U.field,"in",U.value):A.where(U.field,"=",U.value)}let p=await A.limit(T+1).offset(H).get()||[],m=p.length>T,J$=(m?p.slice(0,T):p).map((f)=>r(G$(f,J),x)),C$=L.searchParams.get("include");if(C$)J$=await a$(J$,J,C$,F$);let _J=L.searchParams.get("with_count")==="true",s;if(_J)try{let f=g.selectFrom(Q);if(U.enforced&&!U.bypass&&U.value!=null)f=Array.isArray(U.value)?f.where(U.field,"in",U.value):f.where(U.field,"=",U.value);let b=await f.count(),l=typeof b==="number"?b:Number(b?.count??b);if(Number.isFinite(l))s=l}catch{}let z$={"Content-Type":"application/json"};if(s!==void 0&&!Number.isNaN(s))z$["X-Total-Count"]=String(s);z$["Cache-Control"]=U.enforced&&!U.bypass?"private, no-store":"public, max-age=15, must-revalidate",z$.Vary="Authorization";let jJ=E$(L,Y,T,J$.length,m,s);return new Response(JSON.stringify({data:J$,...jJ,meta:K$(L,Y,T,J$.length,m,s)}),{status:200,headers:z$})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to fetch ${Z}`,detail:String(L)},500)}}));if(z.includes("show")&&!t("GET",`${X}/{id}`))P(i.get(`${X}/{id}`,async(_)=>{try{let L=Y$(_.params?.id);if(L==null)return j({error:"Invalid ID parameter"},400);let Y=await g.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return j({error:`${$} not found`},404);let T=new URL(_.url);if(J.traits?.useSoftDeletes&&Y.deleted_at&&T.searchParams.get("withTrashed")!=="true")return j({error:`${$} not found`},404);let H=V?await e(J,await a(_),_):{enforced:!1,value:null,field:"",bypass:!1};if(H.enforced&&!H.bypass){if(H.value==null||!O$(Y[H.field],H.value))return j({error:`${$} not found`},404)}let N=r(G$(Y,J),x),A=T.searchParams.get("include");if(A){let[S]=await a$([N],J,A,F$);N=S}let w=N?.updated_at||N?.created_at,I=w?`W/"${N.id}-${String(w)}"`:void 0,R=_.headers?.get?.("if-none-match");if(I&&R&&R===I)return new Response(null,{status:304,headers:{ETag:I}});let y={"Content-Type":"application/json"};if(I)y.ETag=I;return y["Cache-Control"]=H.enforced&&!H.bypass?"private, no-store":"public, max-age=30, must-revalidate",y.Vary="Authorization",new Response(JSON.stringify({data:N}),{status:200,headers:y})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to fetch ${$}`,detail:String(L)},500)}}));if(z.includes("store")&&!t("POST",X))P(i.post(X,async(_)=>{try{let L=await V$(_),Y=H$(L,x),T=N$(Y,W),H=await a(_);if(H){let S=await JJ(J,"creating",H,_);for(let[h,U]of Object.entries(S))if(U!==void 0&&U!==null&&T[h]===void 0)T[h]=U}let N=await e(J,H,_);if(N.enforced&&!N.bypass){if(!H)return j({error:"Auth required"},401);let S=c$(T,N.field,N.value);if(S.error)return j({error:S.error},403);T=S.data}if(Object.keys(T).length===0)return j({error:"No fillable fields provided"},422);let A=D$(T,J,"creating");if(!A.valid)return j({success:!1,message:"Validation failed",errors:A.errors},422);if(J.traits?.useTimestamps!==!1){let S=new Date().toISOString();T.created_at=S,T.updated_at=S}let w=await e$(T,J),I=j$($J(w,J)),R=await g.insertInto(Q).values(I).execute(),y=I;try{let S=R?.lastInsertRowid??R?.insertId??R;if(S){let h=await g.selectFrom(Q).where({id:S}).executeTakeFirst();if(h)y=h}}catch{}return j({data:r(G$(y,J),x)},201)}catch(L){let{status:Y,body:T}=_$(L,$,"create");return j(T,Y)}}),D);if(z.includes("update")){let _=async(L)=>{try{let Y=Y$(L.params?.id);if(Y==null)return j({error:"Invalid ID parameter"},400);let T=await V$(L),H=H$(T,x),N=N$(H,W),A=await a(L);if(A){let U=await JJ(J,"updating",A,L);for(let[p,m]of Object.entries(U))if(m!==void 0&&m!==null&&N[p]===void 0)N[p]=m}if(Object.keys(N).length===0)return j({error:"No fillable fields provided"},422);let w=D$(N,J,"updating");if(!w.valid)return j({success:!1,message:"Validation failed",errors:w.errors},422);let I=await g.selectFrom(Q).where({id:Y}).executeTakeFirst();if(!I)return j({error:`${$} not found`},404);let R=await e(J,A,L);if(R.enforced&&!R.bypass){if(!A)return j({error:"Auth required"},401);let U=I[R.field];if(!O$(U,R.value))return j({error:`Not your ${$}`},403);let p=Object.keys(N).find((m)=>F(m)===F(R.field));if(p!==void 0&&!O$(N[p],R.value))return j({error:`Cannot reassign ${$} ownership`},403)}if(J.traits?.useTimestamps!==!1)N.updated_at=new Date().toISOString();let y=await e$(N,J),S=j$($J(y,J));await g.updateTable(Q).set(S).where({id:Y}).execute();let h={...I,...S};try{let U=await g.selectFrom(Q).where({id:Y}).executeTakeFirst();if(U)h=U}catch{}return j({data:r(G$(h,J),x)})}catch(Y){let{status:T,body:H}=_$(Y,$,"update");return j(H,T)}};if(!t("PUT",`${X}/{id}`))P(i.put(`${X}/{id}`,_),D);if(!t("PATCH",`${X}/{id}`))P(i.patch(`${X}/{id}`,_),D)}let M=!!J.traits?.useSoftDeletes;if(z.includes("destroy")&&!t("DELETE",`${X}/{id}`))P(i.delete(`${X}/{id}`,async(_)=>{try{let L=Y$(_.params?.id);if(L==null)return j({error:"Invalid ID parameter"},400);let Y=await g.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return j({error:`${$} not found`},404);let T=await a(_),H=await e(J,T,_);if(H.enforced&&!H.bypass){if(!T)return j({error:"Auth required"},401);let N=Y[H.field];if(!O$(N,H.value))return j({error:`Not your ${$}`},403)}if(M){let N=new Date().toISOString();await g.updateTable(Q).set({deleted_at:N,updated_at:N}).where({id:L}).execute()}else await g.deleteFrom(Q).where({id:L}).execute();return new Response(null,{status:204})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to delete ${$}`,detail:String(L)},500)}}),D);if(z.includes("destroy")&&!t("POST",`${X}/bulk-delete`))P(i.post(`${X}/bulk-delete`,async(_)=>{try{let Y=(await V$(_))?.ids;if(!Array.isArray(Y)||Y.length===0)return j({error:"An array of IDs is required"},422);if(Y.length>100)return j({error:"Cannot delete more than 100 records at once"},422);let T=[],H=[];for(let I of Y){let R=Y$(I);if(R!=null)T.push(R);else H.push(I)}if(H.length>0)return j({error:"Invalid IDs in batch",invalid:H},422);let N=await a(_),A=await e(J,N,_);if(A.enforced&&!A.bypass){if(!N)return j({error:"Auth required"},401);if(A.value==null)return j({error:"Caller has no ownership identity"},403);let I=await g.selectFrom(Q).select(["id",A.field]).execute(),R=new Set(I.filter((S)=>O$(S[A.field],A.value)).map((S)=>String(S.id))),y=T.filter((S)=>!R.has(String(S)));if(y.length>0)return j({error:`Cannot delete ${$} you don't own`,ids:y},403)}let w=new Date().toISOString();for(let I of T)if(M)await g.updateTable(Q).set({deleted_at:w,updated_at:w}).where({id:I}).execute();else await g.deleteFrom(Q).where({id:I}).execute();return j({message:`Successfully deleted ${T.length} ${Z}`})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to bulk delete ${Z}`,detail:String(L)},500)}}),D)}QJ=i});var WJ={};Q$(WJ,{default:()=>QJ});var KJ=d(async()=>{await LJ()});class R${data;status;headers;isOk;constructor($,J,O,G){this.data=$;this.status=J;this.headers=O;this.isOk=G}ok(){return this.status===200}created(){return this.status===201}accepted(){return this.status===202}noContent(){return this.status===204}movedPermanently(){return this.status===301}found(){return this.status===302}badRequest(){return this.status===400}unauthorized(){return this.status===401}paymentRequired(){return this.status===402}forbidden(){return this.status===403}notFound(){return this.status===404}requestTimeout(){return this.status===408}conflict(){return this.status===409}unprocessableEntity(){return this.status===422}tooManyRequests(){return this.status===429}serverError(){return this.status===500}}class k${defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams($){return this.queryParams=$,this}withHeaders($){return this.customHeaders={...this.customHeaders,...$},this}accept($){return this.defaultHeaders.Accept=$,this}acceptJson(){return this.accept("application/json")}withToken($){return this.customHeaders.Authorization=`Bearer ${$}`,this}withBasicAuth($,J){let O=btoa(`${$}:${J}`);return this.customHeaders.Authorization=`Basic ${O}`,this}withDigestAuth($,J){return this.digestAuth={username:$,password:J},this}withBody($){return this.bodyData=$,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach($,J,O,G){let Z=typeof J==="string"?new Blob([J],{type:G?.["Content-Type"]||"text/plain"}):J;return this.attachments.push({name:$,content:Z,filename:O,headers:G}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams($){if(!this.queryParams)return $;let J=new URLSearchParams;Object.entries(this.queryParams).forEach(([Z,z])=>{if(z!=null)J.append(Z,String(z))});let O=J.toString();if(!O)return $;let G=$.includes("?");return $+(G?"&":"?")+O}async formatBody($){let J=$||this.bodyData;if(this.isMultipart){let O=new FormData;if(J)Object.entries(J).forEach(([G,Z])=>{O.append(G,String(Z))});for(let G of this.attachments)if(G.headers){let Z=G.content instanceof Blob?new Blob([G.content],{type:G.headers["Content-Type"]}):G.content;O.append(G.name,Z,G.filename)}else O.append(G.name,G.content,G.filename);return O}if(this.isFormData&&J){let O=new URLSearchParams;return Object.entries(J).forEach(([G,Z])=>{if(Z!=null)O.append(G,String(Z))}),O.toString()}return J?JSON.stringify(J):void 0}resetState(){this.queryParams=void 0,this.bodyData=void 0,this.isFormData=!1,this.isMultipart=!1,this.customHeaders={},this.attachments=[],this.digestAuth=void 0,this.defaultHeaders["Content-Type"]="application/json"}async handleDigestAuth($,J,O,G){if($.status!==401||!this.digestAuth)return $;let Z=$.headers.get("WWW-Authenticate");if(!Z?.startsWith("Digest "))return $;let z=Z.substring(7).split(",").reduce((C,E)=>{let[k,V]=E.trim().split("=");if(k)C[k]=V?.replace(/["']/g,"")??"";return C},{}),Q=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),W=await this.generateMD5(`${O}:${J}`),x="00000001",X=await this.generateMD5(Date.now().toString()).then((C)=>C.substring(0,8)),K=await this.generateMD5(`${Q}:${z.nonce}:${x}:${X}:${z.qop}:${W}`),B={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${J}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:x,cnonce:`"${X}"`,response:`"${K}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},D=Object.entries(B).filter(([C,E])=>E!==void 0).map(([C,E])=>`${C}=${E}`).join(", ");return this.customHeaders.Authorization=`Digest ${D}`,fetch(J,{method:O,headers:this.getHeaders(),body:G?this.formatBody(G):void 0})}async generateMD5($){let O=new TextEncoder().encode($),G=await crypto.subtle.digest("SHA-256",O);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,J,O){let G=this.addQueryParams($),Z=await this.formatBody(O),z=await fetch(G,{method:J,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,G,J,O);let Q=await z.json();return this.resetState(),new R$(Q,z.status,z.headers,z.ok)}async get($){return this.request($,"GET")}async post($,J){return this.request($,"POST",J)}async put($,J){return this.request($,"PUT",J)}async patch($,J){return this.request($,"PATCH",J)}async delete($){return this.request($,"DELETE")}}var rJ=new k$;B$();import{path as $$}from"@stacksjs/path";function YJ($){if(!$||typeof $!=="object")return{type:"string"};let J=$,O=Array.isArray(J.rules)?J.rules:[],G=(K)=>O.find((B)=>B.name===K),Z=(K,B)=>{let D=G(K)?.params?.[B];return typeof D==="number"?D:void 0},z=J.name??J._type??"string",Q={type:z==="enum"?"string":z},W=Z("min","min")??(typeof J._min==="number"?J._min:void 0),x=Z("max","max")??(typeof J._max==="number"?J._max:void 0);if(W!==void 0)Q[z==="string"?"minLength":"minimum"]=W;if(x!==void 0)Q[z==="string"?"maxLength":"maximum"]=x;if(G("email")||J._email)Q.format="email";if(G("url")||J._url)Q.format="uri";if(G("uuid")||J._uuid)Q.format="uuid";let X=Array.isArray(J.allowedValues)?J.allowedValues:Array.isArray(J._enum)?J._enum:null;if(X)Q.enum=X;return Q}function nJ($){if(!$||typeof $!=="object")return!1;let J=$;return Boolean(J.isRequired??J._required)}function XJ($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function uJ($){let J={id:{type:"integer"}},O=["id"];if($.traits?.useUuid)J.uuid={type:"string",format:"uuid"},O.push("uuid");for(let[G,Z]of Object.entries($.attributes??{})){if(Z.hidden===!0)continue;let z=XJ(G);if(J[z]=YJ(Z.validation?.rule),Z.required===!0)O.push(z)}for(let G of $.belongsTo??[]){if(typeof G!=="string"||!G.trim())continue;let Z=`${XJ(G.trim())}_id`;J[Z]??={type:"integer"}}if($.traits?.useTimestamps!==!1)J.created_at={type:"string",format:"date-time"},J.updated_at={type:"string",format:"date-time"};if($.traits?.useSoftDeletes)J.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties:J,required:[...new Set(O)]}}function lJ($){let J=$.traits?.useApi;if(!J||typeof J!=="object"||!J.uri)return null;let O=String(J.prefix||"").replace(/^\/+|\/+$/g,""),G=String(J.uri).replace(/^\/+|\/+$/g,"");return`/api/${O?`${O}/`:""}${G}`}function oJ($,J){let O={...J},G=$?.responses;if(G&&typeof G==="object")for(let[z,Q]of Object.entries(G)){let W=Q;if(!W||typeof W!=="object"||typeof W.description!=="string")continue;O[String(z)]={description:W.description,...W.schema&&typeof W.schema==="object"?{content:{"application/json":{schema:W.schema}}}:{}}}let Z=$?.responseHeaders;if(Z&&typeof Z==="object"){let z={};for(let[Q,W]of Object.entries(Z)){let x=W;if(!x||typeof x!=="object"||typeof x.description!=="string")continue;z[Q]={description:x.description,...x.schema&&typeof x.schema==="object"?{schema:x.schema}:{}}}if(Object.keys(z).length>0)for(let Q of Object.keys(O))O[Q]={...O[Q],headers:z}}return O}async function tJ($){if(typeof $!=="string"||!$||$.includes(".."))return null;try{let{path:J}=await import("@stacksjs/path"),O=[J.appPath(`${$}.ts`),J.storagePath(`framework/defaults/app/${$}.ts`)];for(let G of O)try{if(!await Bun.file(G).exists())continue;let Q=(await import(G)).default;return Q&&typeof Q==="object"?Q:null}catch{}}catch{}return null}async function _O($={}){let J=$.portable??!0,{listRegisteredRoutes:O}=await import("@stacksjs/router");try{let{loadRoutes:K}=await import("@stacksjs/router"),{default:B}=await import($$.appPath("Routes.ts"));await K(B)}catch(K){let B=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${B}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${B}`)}try{try{await import("@stacksjs/orm/routes")}catch{await KJ().then(() => WJ)}}catch(K){let B=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${B}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${B}`)}let G={};try{let B;try{B=await import("@stacksjs/orm/model-registry")}catch{B=await Promise.resolve().then(() => (I$(),t$))}G=await B.loadModelRegistry({defaultsRoot:$$.storagePath("framework/defaults/app/Models"),userRoot:$$.projectPath("app/Models")})}catch(K){let B=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${B}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${B}`)}let Z=(K)=>K.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),z=[...O()].map((K)=>({route:K,oasPath:Z(K.path),method:K.method.toLowerCase()})).sort((K,B)=>{if(K.oasPath!==B.oasPath)return K.oasPath<B.oasPath?-1:1;return K.method<B.method?-1:K.method>B.method?1:0});if(J&&z.length===0)throw Error("[generateOpenApi] Refusing to emit an empty spec: no routes were registered. This usually means route loading failed silently rather than that the app has no API.");let Q="Stacks API";if(!J)try{let{config:K}=await import("@stacksjs/config");if(K.app?.name)Q=`${K.app.name} API`}catch{}let W={openapi:"3.0.0",info:{title:Q,version:"1.0.0"},paths:{},components:{schemas:{}}},x=Object.values(G).map((K)=>({name:String(K.name),path:lJ(K),schema:uJ(K)})).filter((K)=>K.path!==null).sort((K,B)=>K.name<B.name?-1:K.name>B.name?1:0);for(let K of x)W.components.schemas[K.name]=K.schema;let X=new Set;for(let{route:K,oasPath:B,method:D}of z){if(!W.paths[B])W.paths[B]={};let C=[];for(let L of K.path.matchAll(/\{(\w+)\}/g))if(L[1])C.push(L[1]);for(let L of K.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(L[1])C.push(L[1]);let E=K.name??`${D}_${B.replace(/[^a-z0-9]/gi,"_")}`,k=E;if(X.has(k)){k=`${E}_${D}`;let L=2;while(X.has(k))k=`${E}_${D}_${L++}`}X.add(k);let V={summary:K.name??K.path,operationId:k,parameters:C.map((L)=>({name:L,in:"path",required:!0,schema:{type:"string"}})),responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object"}}}},422:{description:"Validation failed"},500:{description:"Server error"}}},q=x.find((L)=>B===L.path||B===`${L.path}/{id}`);if(q){let L=B===q.path&&D==="get"?{type:"array",items:q.schema}:q.schema;if(V.responses[200].content={"application/json":{schema:{type:"object",properties:{data:L},required:["data"]}}},D==="post"&&B===q.path)V.responses[201]={...V.responses[200],description:"Created"},delete V.responses[200]}let P=K.handler?await tJ(K.handler):null,M=P&&typeof P.validations==="object"&&P.validations!==null?P.validations:null;V.responses=oJ(P,V.responses);let _=P?.requestHeaders;if(_&&typeof _==="object")for(let[L,Y]of Object.entries(_)){let T=Y;if(!T||typeof T!=="object"||typeof T.description!=="string")continue;V.parameters?.push({name:L,in:"header",description:T.description,required:T.required===!0,schema:T.schema&&typeof T.schema==="object"?T.schema:{type:"string"}})}if(M&&Object.keys(M).length>0){let L=Object.entries(M).map(([Y,T])=>{let H=T?.rule;return{field:Y,schema:YJ(H),required:nJ(H)}});if(D==="get"||D==="head"||D==="delete"){let Y=new Set(C);for(let{field:T,schema:H,required:N}of L){if(Y.has(T))continue;V.parameters?.push({name:T,in:"query",required:N,schema:H})}}else{let Y={type:"object",properties:{},required:[]},T=Y.properties,H=Y.required;for(let N of L)if(T[N.field]=N.schema,N.required)H.push(N.field);if(H.length===0)delete Y.required;V.requestBody={required:H.length>0,content:{"application/json":{schema:Y}}}}}W.paths[B][D]=V}if($.write!==!1){await Bun.write($$.frameworkPath("api/openapi.json"),JSON.stringify(W,null,2));let{renderOpenApiTypes:K}=await Promise.resolve().then(() => (L$(),f$)),{renderApiClient:B}=await Promise.resolve().then(() => (B$(),g$));await Bun.write($$.frameworkPath("api/api-types.ts"),K(W)),await Bun.write($$.frameworkPath("api/client.ts"),B(W,{name:W.info.title}))}return W}L$();class v{static instance=new v;isMissing(){return!0}}class Z${data;constructor($){this.data=$}}class xJ{condition;value;defaultValue;constructor($,J,O=new v){this.condition=$;this.value=J;this.defaultValue=O}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class BJ{resource;additional={};request;static wrap="data";static additionalMeta={};constructor($){this.resource=$}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=this.toArray($||this.request);return this.filterAndResolve(J)}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{...J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}toJSON(){return this.toResponse()}static collection($){return new M$($,this)}when($,J,O){if(typeof $==="function"?$():$)return typeof J==="function"?J():J;return O!==void 0?O:v.instance}whenNotNull($,J){if($===null||$===void 0)return v.instance;return J?J($):$}whenLoaded($,J,O){let G=this.resource;if(!(($ in G)&&G[$]!==void 0))return O!==void 0?O:v.instance;if(J!==void 0)return typeof J==="function"?J():J;return G[$]}whenCounted($,J){let O=this.resource,G=`${$}_count`;if(G in O)return O[G];return J!==void 0?J:v.instance}merge($){return new Z$($)}mergeWhen($,J){if(!(typeof $==="function"?$():$))return v.instance;let G=typeof J==="function"?J():J;return new Z$(G)}static MAX_RESOLVE_DEPTH=20;filterAndResolve($,J=0){if(J>=BJ.MAX_RESOLVE_DEPTH)return $;let O={};for(let[G,Z]of Object.entries($)){if(Z instanceof v)continue;if(Z instanceof Z$){Object.assign(O,this.filterAndResolve(Z.data,J+1));continue}if(Z instanceof xJ){let z=Z.resolve();if(!(z instanceof v))O[G]=z;continue}if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&!(Z instanceof Date)){O[G]=this.filterAndResolve(Z,J+1);continue}if(Array.isArray(Z)){O[G]=Z.filter((z)=>!(z instanceof v)).map((z)=>{if(z instanceof Z$)return z.data;if(z!==null&&typeof z==="object"&&!(z instanceof Date))return this.filterAndResolve(z,J+1);return z});continue}O[G]=Z}return O}static withoutWrapping(){this.wrap=null}static wrapWith($){this.wrap=$}}class M${resources;ResourceClass;additional={};request;static wrap="data";constructor($,J){this.resources=$,this.ResourceClass=J}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=$||this.request;return this.resources.map((O)=>{let G=new this.ResourceClass(O);if(J)G.withRequest(J);return G.resolve(J)})}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{data:J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class TJ extends M${meta;links;constructor($,J){super($.data,J);this.meta=$.meta,this.links=$.links}static fromPagination($,J,O){let{currentPage:G,perPage:Z,total:z,baseUrl:Q=""}=O,W=Math.ceil(z/Z),x=z>0?(G-1)*Z+1:null,X=z>0?Math.min(G*Z,z):null;return new TJ({data:$,meta:{current_page:G,from:x,last_page:W,per_page:Z,to:X,total:z},links:{first:`${Q}?page=1`,last:`${Q}?page=${W}`,prev:G>1?`${Q}?page=${G-1}`:null,next:G<W?`${Q}?page=${G+1}`:null}},J)}toResponse($){return{data:this.resolve($),meta:this.meta,links:this.links,...this.additional}}}function NO($,J){let O=J($);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}function HO($,J){let O=$.map(J);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}export{c as schemaType,YJ as ruleToSchema,nJ as ruleIsRequired,NO as resource,IJ as renderOpenApiTypes,RJ as renderApiClient,uJ as modelDefinitionToSchema,b$ as methodName,_O as generateOpenApi,rJ as fetcher,oJ as describedResponses,HO as collection,M$ as ResourceCollection,TJ as PaginatedResourceCollection,v as MissingValue,Z$ as MergeValue,BJ as JsonResource,xJ as ConditionalValue};
139
+ `}var Tt;var ge=Z(()=>{ce();Tt=["get","put","post","delete","options","head","patch"]});function vt(e){let t=e;return t?.code==="SQLITE_CONSTRAINT_UNIQUE"||t?.code==="SQLITE_CONSTRAINT"||t?.code==="23505"||t?.errno===1062||/unique|duplicate/i.test(t?.message??"")}function me(e,t,n){let r=e;if(e instanceof Error&&typeof r.status==="number"&&Number.isInteger(r.status)&&r.status>=400&&r.status<600){let s={error:e.message};if(r.details!==void 0)s.details=r.details;return{status:r.status,body:s}}if(vt(e))return{status:409,body:{error:`${t} already exists`}};return{status:500,body:{error:`Failed to ${n} ${t}`,detail:String(e)}}}function T(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ye(e){let t={};for(let[n,r]of Object.entries(e))t[T(n)]=r;return t}function Ee(e,t){let n=String(t||"").replace(/^\/+|\/+$/g,""),r=String(e).replace(/^\/+/,"");return`/api/${n?`${n}/`:""}${r}`}function Be(e){if(!e)return null;let t=e.attributes??{};if(Object.prototype.hasOwnProperty.call(t,"teamId")||Object.prototype.hasOwnProperty.call(t,"team_id"))return"team_id";return e.belongsTo?.some((n)=>n==="Team")?"team_id":null}function Me(e,t,n){let r=Object.keys(e).find((o)=>T(o)===T(t));if(Array.isArray(n)){if(r===void 0)return{data:e,error:"Ownership value is required"};if(!n.some((o)=>String(o)===String(e[r])))return{data:e,error:"Ownership value is not available to this caller"};return{data:{...e,[t]:e[r]}}}if(n===null||n===void 0)return{data:e,error:"Caller has no ownership identity"};let s={...e};for(let o of Object.keys(s))if(T(o)===T(t))delete s[o];return s[t]=n,{data:s}}function Fe(e){if(!e)return[];let t=Object.entries(e.attributes??{}).filter(([,n])=>n?.fillable===!0).map(([n])=>n);for(let n of e.belongsTo??[]){if(typeof n!=="string"||!n.trim())continue;let r=T(n.trim()).split("_").filter(Boolean);if(r.length===0)continue;let s=`${r[0]}${r.slice(1).map((o)=>`${o[0]?.toUpperCase()}${o.slice(1)}`).join("")}Id`;t.push(s)}return[...new Set(t)]}function be(e,t){if(!e||t.length===0)return{};let n={};for(let r of t){if(r in e){n[r]=e[r];continue}let s=T(r);if(s!==r&&s in e)n[r]=e[s]}return n}function qt(e,t){if(e?.name!=="date"||t instanceof Date||typeof t!=="string")return t;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return t;let r=Number(n[1]),s=Number(n[2]),o=Number(n[3]),i=new Date(Date.UTC(r,s-1,o));if(i.getUTCFullYear()!==r||i.getUTCMonth()!==s-1||i.getUTCDate()!==o)return t;return i}function we(e,t){if(!t.length)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function K(e,t){if(!e||t.length===0)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function Ue(e,t){let n=new Map;for(let r of[...Object.keys(e??{}),...Dt]){let s=T(r);if(!/^\w+$/.test(s))continue;n.set(r,s),n.set(s,s)}for(let r of t)n.delete(r),n.delete(T(r));return n}function Je(e,t,n){if(!t)return e;let r=String(t).split(",").map((o)=>o.trim()).filter(Boolean),s=e;for(let o of r){let i=o.startsWith("-"),c=i?o.slice(1):o;if(!/^\w+$/.test(c))continue;let p=n.get(c);if(!p)continue;s=s.orderBy(p,i?"desc":"asc")}return s}function Ct(e){try{return JSON.parse(e)}catch{return e}}function It(e){try{return JSON.parse(e)}catch{return[]}}function Re(e,t,n){if(!e||typeof e!=="object"||!t||Object.keys(t).length===0)return e;let r={...e};for(let[s,o]of Object.entries(t)){let i=typeof o==="string"?Nt[o]:o;if(!i||typeof i[n]!=="function")continue;if(Object.prototype.hasOwnProperty.call(r,s))r[s]=i[n](r[s]);let c=T(s);if(c!==s&&Object.prototype.hasOwnProperty.call(r,c))r[c]=i[n](r[c])}return r}function Oe(e,t,n){let r=t?.attributes??{},s={};for(let[o,i]of Object.entries(r)){let c=i?.validation?.rule;if(!c||typeof c.validate!=="function")continue;let p=Object.prototype.hasOwnProperty.call(e,o);if(!p&&n==="updating")continue;let d=i!==null&&typeof i==="object"&&Object.prototype.hasOwnProperty.call(i,"default"),u=p?e[o]:d?i.default:void 0,f=qt(c,u),R=c.validate(f);if(!R?.valid&&Array.isArray(R?.errors)&&R.errors.length>0)s[o]=R.errors.map((P)=>i?.validation?.message?.[P?.code]??P?.message??"invalid")}return Object.keys(s).length===0?{valid:!0}:{valid:!1,errors:s}}function Se(e){return e.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function he(e){if(Array.isArray(e))return e.filter((t)=>typeof t==="string"&&t.length>0);return typeof e==="string"&&e?[e]:[]}function He(e){let t=typeof e==="object"&&e!==null&&"middleware"in e,n=e?.middleware;if(!t)return{read:["auth"],write:["auth"],declared:!1};if(n&&typeof n==="object"&&!Array.isArray(n)){let s=n;return{read:"read"in s?he(s.read):["auth"],write:"write"in s?he(s.write):["auth"],declared:!0}}let r=he(n);return{read:r,write:r,declared:!0}}function Le(e){let t=Number.parseInt(e.get("page")||String(1),10),n=Number.isFinite(t)?Math.max(1,t):1,r=Number.parseInt(e.get("per_page")||String(Ie),10),s=Math.min(Number.isFinite(r)?Math.max(1,r):Ie,Et);return{page:n,perPage:s,offset:(n-1)*s}}function ue(e,t){let n=new URL(e.toString());return n.searchParams.set("page",String(t)),`${n.pathname}${n.search}`}function de(e,t,n,r,s,o){let i=(t-1)*n,c=r===0,p={page:t,per_page:n,from:c?null:i+1,to:c?null:i+r,has_more_pages:s,prev_page_url:t>1?ue(e,t-1):null,next_page_url:s?ue(e,t+1):null};if(o!==void 0&&!Number.isNaN(o)){let d=Math.max(1,Math.ceil(o/n));p.total=o,p.last_page=d,p.first_page_url=ue(e,1),p.last_page_url=ue(e,d)}return p}function ke(e,t,n,r,s,o){let{page:i,...c}=de(e,t,n,r,s,o);return{current_page:i,...c}}var Dt,Nt,Ie=15,Et=100;var We=Z(()=>{Dt=["id","uuid","created_at","updated_at","deleted_at"];Nt={string:{get:(e)=>e!=null?String(e):null,set:(e)=>e!=null?String(e):null},number:{get:(e)=>e!=null?Number(e):null,set:(e)=>e!=null?Number(e):null},integer:{get:(e)=>e!=null?Math.trunc(Number(e)):null,set:(e)=>e!=null?Math.trunc(Number(e)):null},float:{get:(e)=>e!=null?Number.parseFloat(String(e)):null,set:(e)=>e!=null?Number.parseFloat(String(e)):null},boolean:{get:(e)=>e===1||e==="1"||e===!0||e==="true",set:(e)=>e===!0||e===1||e==="1"||e==="true"?1:0},json:{get:(e)=>e==null?null:typeof e==="string"?Ct(e):e,set:(e)=>e==null?null:typeof e==="string"?e:JSON.stringify(e)},datetime:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString():e},date:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString().split("T")[0]:e},array:{get:(e)=>e==null?[]:Array.isArray(e)?e:typeof e==="string"?It(e):[],set:(e)=>e==null?null:Array.isArray(e)?JSON.stringify(e):e}}});var Ge={};ae(Ge,{loadModelRegistry:()=>$e,modelFiles:()=>Qe});import{readdirSync as Bt}from"fs";import{basename as Mt,extname as Ve,join as Ft}from"path";function Qe(e){let t=[],n=(r)=>{let s;try{s=Bt(r,{withFileTypes:!0})}catch{return}for(let o of s){let i=Ft(r,o.name);if(o.isDirectory()){n(i);continue}if(![".ts",".js"].includes(Ve(o.name)))continue;if(o.name.startsWith(".")||o.name.startsWith("index"))continue;t.push(i)}};return n(e),t.sort()}async function ze(e,t,n){for(let r of Qe(e))try{let s=Ve(r),o=await import(`${r}?t=${Date.now()}`),i=o.default??o,c=i.name??Mt(r,s);t[c]={...i,name:c}}catch(s){n?.(r,s)}}async function $e(e){let t={};return await ze(e.defaultsRoot,t,e.onImportError),await ze(e.userRoot,t,e.onImportError),t}var Ae=()=>{};import{route as L}from"@stacksjs/router";import{env as Q}from"@stacksjs/env";import{projectPath as rt,storagePath as Ut}from"@stacksjs/path";import{createQueryBuilder as Jt,defaultConfig as Xe,setConfig as Ze}from"@stacksjs/query-builder";import{HttpError as z}from"@stacksjs/error-handling";import{log as fe}from"@stacksjs/logging";function G(e,t){let n=Se(t);return L.routes.some((r)=>r.method===e&&Se(String(r.path??""))===n)}function st(e){if(!e.attributes)return[];return Object.entries(e.attributes).filter(([t,n])=>n.hidden===!0).map(([t])=>t)}function Ke(e){if(e.endsWith("y")&&!/[aeiou]y$/i.test(e))return`${e.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test(e))return`${e}es`;return`${e}s`}async function Ye(e,t,n,r){if(!e.length)return e;let s=n.split(",").map((d)=>d.trim()).filter(Boolean);if(!s.length)return e;let o=Array.isArray(t.belongsTo)?t.belongsTo:[],i=Array.isArray(t.hasMany)?t.hasMany:[],c=Array.isArray(t.hasOne)?t.hasOne:[],p=new Map;for(let d of o)p.set(T(d),{kind:"belongsTo",modelName:d});for(let d of c)p.set(T(d),{kind:"hasOne",modelName:d});for(let d of i)p.set(Ke(T(d)),{kind:"hasMany",modelName:d});for(let d of s){let u=p.get(d);if(!u)continue;let f=r[u.modelName];if(!f)continue;let R=f.table||Ke(T(u.modelName)),P=st(f),S=(v)=>K(se(v,f),P);if(u.kind==="belongsTo"||u.kind==="hasOne"){let v=`${T(u.modelName)}_id`,j=[...new Set(e.map((x)=>x[v]).filter((x)=>x!=null))];if(!j.length){for(let x of e)x[d]=null;continue}let E=await C.selectFrom(R).whereIn("id",j).get(),q=new Map;for(let x of E??[])q.set(String(x.id),S(x));for(let x of e)x[d]=q.get(String(x[v]))??null}else{let v=String(t.name??""),j=`${T(v)}_id`,E=[...new Set(e.map((h)=>h.id).filter((h)=>h!=null))];if(!E.length){for(let h of e)h[d]=[];continue}let q=await C.selectFrom(R).whereIn(j,E).get(),x=new Map;for(let h of q??[]){let a=String(h[j]),l=x.get(a)??[];l.push(S(h)),x.set(a,l)}for(let h of e)h[d]=x.get(String(h.id))??[]}}return e}async function et(e,t){let n=t?.set;if(!n||typeof n!=="object")return e;let r={...e};for(let[s,o]of Object.entries(n)){if(typeof o!=="function"||!(s in r))continue;try{r[s]=await o(r)}catch{}}return r}function tt(e,t){return Re(e,t?.casts,"set")}function se(e,t){return Re(e,t?.casts,"get")}function m(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}async function je(e){if(Number(e.headers?.get?.("content-length")??0)>le)throw new z(413,`Request body exceeds ${le}-byte limit`);if(e.jsonBody&&typeof e.jsonBody==="object")return e.jsonBody;if(e.formBody&&typeof e.formBody==="object")return e.formBody;try{let n=await e.clone().text();if(n.length>le)throw new z(413,`Request body exceeds ${le}-byte limit`);if(!n)return{};let r=JSON.parse(n);return r&&typeof r==="object"&&!Array.isArray(r)?r:{}}catch(n){if(n instanceof z)throw n;throw new z(400,`Invalid JSON body: ${n.message}`)}}function pe(e){if(e==null)return null;if(typeof e==="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e==="string"){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)&&n>0?n:null}return t}return null}function ot(e){let t=e.bearerToken;if(typeof t==="function"){let r=t.call(e);if(r)return r}let n=e.headers?.get?.("authorization")||e.headers?.get?.("Authorization")||"";if(typeof n==="string"&&n.startsWith("Bearer "))return n.substring(7);return null}async function Y(e){let t=e._authenticatedUser;if(t)return t;let n=ot(e);if(!n)return null;try{let{Auth:r}=await import("@stacksjs/auth"),s=await r.getUserFromToken(n);if(s)e._authenticatedUser=s;return s||null}catch{return null}}function re(e,t){if(e==null||t==null)return!1;if(Array.isArray(t))return t.some((n)=>String(n)===String(e));return String(e)===String(t)}function Lt(e){let t=ot(e),n=e.headers?.get?.("cookie")||"";return{bearerToken:()=>t,cookies:{get:(r)=>{for(let s of n.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()===r)return decodeURIComponent(s.slice(o+1).trim())}return null}}}}function it(e){if(e?.ownership)return e.ownership;let t=Be(e);if(!t)return null;return{field:t,resolve:async(n,r)=>{let{resolveAuthenticatedTeamId:s}=await import("@stacksjs/auth");return s(Lt(r))}}}async function ee(e,t,n){let r=it(e);if(!r||!r.field||typeof r.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let s=typeof r.bypass==="function"?!!r.bypass(t,n):!1,o=null;try{o=await r.resolve(t,n)}catch{o=null}return{enforced:!0,value:o,field:String(r.field),bypass:s}}async function nt(e,t,n,r){let s=e?.authedFill?.[t];if(!s)return{};if(typeof s==="function")try{let o=await s(n,r);return o&&typeof o==="object"?o:{}}catch{return{}}if(typeof s==="object"){let o={};for(let[i,c]of Object.entries(s))try{o[i]=typeof c==="function"?await c(n,r):c}catch{}return o}return{}}var Ht,Te,C,le=1048576,at;var ct=Z(async()=>{We();Ae();Ht=rt("config/qb.ts");try{let e=(await import(Ht)).default;Ze(e??Xe)}catch{fe.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let e=Q.DB_CONNECTION||"sqlite";Ze({...Xe,dialect:e,database:e==="sqlite"?{database:Q.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:Q.DB_DATABASE||"stacks",host:Q.DB_HOST||"127.0.0.1",port:Q.DB_PORT||(e==="postgres"?5432:3306),username:Q.DB_USERNAME||(e==="postgres"?"postgres":"root"),password:Q.DB_PASSWORD||""}})}Te=await $e({defaultsRoot:Ut("framework/defaults/app/Models"),userRoot:rt("app/Models"),onImportError:(e,t)=>fe.warn(`[orm] Could not load model ${e}: ${t.message}`)}),C=Jt();for(let[e,t]of Object.entries(Te)){let n=t.traits?.useApi;if(!n)continue;let r=typeof n==="object"?n:{},s=r.uri||t.table||e.toLowerCase()+"s",o=r.routes||["index","show","store","update","destroy"],i=t.table||s,c=Fe(t),p=st(t),d=Ee(s,r.prefix),u=Ue(t.attributes,p),{read:f,write:R,declared:P}=He(n);if(["store","update","destroy"].some((h)=>o.includes(h))&&P&&R.length===0)fe.warn(`[orm] ${e}: registering UNAUTHENTICATED mutating routes at ${d} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((h)=>o.includes(h))&&P&&f.length===0)fe.debug(`[orm] ${e}: registering public read routes at ${d} (declared \`middleware.read: []\`)`);let j=!!it(t),E=j&&!f.includes("auth")?["auth",...f]:f,q=(h,a=E)=>{let l=h;for(let g of a)if(l&&typeof l.middleware==="function")l=l.middleware(g);return l};if(o.includes("index")&&!G("GET",d))q(L.get(d,async(h)=>{try{let a=new URL(h.url),{page:l,perPage:g,offset:b}=Le(a.searchParams),y=a.searchParams.get("sort"),w=C.selectFrom(i);w=Je(w,y,u);let B=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[D,N]of a.searchParams.entries()){if(B.has(D)||!N)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(D))continue;let V=u.get(D);if(V)w=w.where(V,"=",N)}let A=a.searchParams.get("search");if(A&&c.length>0){let D=c.slice(0,5);w=w.where((N)=>{for(let V of D)N=N.orWhere(T(V),"like",`%${A}%`);return N})}let _=a.searchParams.get("fields");if(_){let D=_.split(",").map((N)=>N.trim()).filter((N)=>/^[a-z_][a-z0-9_]*$/i.test(N)).map((N)=>T(N));if(D.length>0)w=w.select(D)}let I=!!t.traits?.useSoftDeletes,k=a.searchParams.get("withTrashed")==="true",U=a.searchParams.get("onlyTrashed")==="true";if(I&&!k)w=U?w.whereNotNull("deleted_at"):w.whereNull("deleted_at");let O=j?await ee(t,await Y(h),h):{enforced:!1,value:null,field:"",bypass:!1};if(O.enforced&&!O.bypass){if(O.value==null||Array.isArray(O.value)&&O.value.length===0){let D=ke(a,l,g,0,!1,void 0);return new Response(JSON.stringify({data:[],...D,meta:de(a,l,g,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}w=Array.isArray(O.value)?w.where(O.field,"in",O.value):w.where(O.field,"=",O.value)}let J=await w.limit(g+1).offset(b).get()||[],H=J.length>g,ne=(H?J.slice(0,g):J).map((D)=>K(se(D,t),p)),Pe=a.searchParams.get("include");if(Pe)ne=await Ye(ne,t,Pe,Te);let mt=a.searchParams.get("with_count")==="true",X;if(mt)try{let D=C.selectFrom(i);if(O.enforced&&!O.bypass&&O.value!=null)D=Array.isArray(O.value)?D.where(O.field,"in",O.value):D.where(O.field,"=",O.value);let N=await D.count(),V=typeof N==="number"?N:Number(N?.count??N);if(Number.isFinite(V))X=V}catch{}let ie={"Content-Type":"application/json"};if(X!==void 0&&!Number.isNaN(X))ie["X-Total-Count"]=String(X);ie["Cache-Control"]=O.enforced&&!O.bypass?"private, no-store":"public, max-age=15, must-revalidate",ie.Vary="Authorization";let yt=ke(a,l,g,ne.length,H,X);return new Response(JSON.stringify({data:ne,...yt,meta:de(a,l,g,ne.length,H,X)}),{status:200,headers:ie})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to fetch ${s}`,detail:String(a)},500)}}));if(o.includes("show")&&!G("GET",`${d}/{id}`))q(L.get(`${d}/{id}`,async(h)=>{try{let a=pe(h.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let g=new URL(h.url);if(t.traits?.useSoftDeletes&&l.deleted_at&&g.searchParams.get("withTrashed")!=="true")return m({error:`${e} not found`},404);let b=j?await ee(t,await Y(h),h):{enforced:!1,value:null,field:"",bypass:!1};if(b.enforced&&!b.bypass){if(b.value==null||!re(l[b.field],b.value))return m({error:`${e} not found`},404)}let y=K(se(l,t),p),w=g.searchParams.get("include");if(w){let[k]=await Ye([y],t,w,Te);y=k}let B=y?.updated_at||y?.created_at,A=B?`W/"${y.id}-${String(B)}"`:void 0,_=h.headers?.get?.("if-none-match");if(A&&_&&_===A)return new Response(null,{status:304,headers:{ETag:A}});let I={"Content-Type":"application/json"};if(A)I.ETag=A;return I["Cache-Control"]=b.enforced&&!b.bypass?"private, no-store":"public, max-age=30, must-revalidate",I.Vary="Authorization",new Response(JSON.stringify({data:y}),{status:200,headers:I})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to fetch ${e}`,detail:String(a)},500)}}));if(o.includes("store")&&!G("POST",d))q(L.post(d,async(h)=>{try{let a=await je(h),l=we(a,p),g=be(l,c),b=await Y(h);if(b){let k=await nt(t,"creating",b,h);for(let[U,O]of Object.entries(k))if(O!==void 0&&O!==null&&g[U]===void 0)g[U]=O}let y=await ee(t,b,h);if(y.enforced&&!y.bypass){if(!b)return m({error:"Auth required"},401);let k=Me(g,y.field,y.value);if(k.error)return m({error:k.error},403);g=k.data}if(Object.keys(g).length===0)return m({error:"No fillable fields provided"},422);let w=Oe(g,t,"creating");if(!w.valid)return m({success:!1,message:"Validation failed",errors:w.errors},422);if(t.traits?.useTimestamps!==!1){let k=new Date().toISOString();g.created_at=k,g.updated_at=k}let B=await et(g,t),A=ye(tt(B,t)),_=await C.insertInto(i).values(A).execute(),I=A;try{let k=_?.lastInsertRowid??_?.insertId??_;if(k){let U=await C.selectFrom(i).where({id:k}).executeTakeFirst();if(U)I=U}}catch{}return m({data:K(se(I,t),p)},201)}catch(a){let{status:l,body:g}=me(a,e,"create");return m(g,l)}}),R);if(o.includes("update")){let h=async(a)=>{try{let l=pe(a.params?.id);if(l==null)return m({error:"Invalid ID parameter"},400);let g=await je(a),b=we(g,p),y=be(b,c),w=await Y(a);if(w){let O=await nt(t,"updating",w,a);for(let[J,H]of Object.entries(O))if(H!==void 0&&H!==null&&y[J]===void 0)y[J]=H}if(Object.keys(y).length===0)return m({error:"No fillable fields provided"},422);let B=Oe(y,t,"updating");if(!B.valid)return m({success:!1,message:"Validation failed",errors:B.errors},422);let A=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(!A)return m({error:`${e} not found`},404);let _=await ee(t,w,a);if(_.enforced&&!_.bypass){if(!w)return m({error:"Auth required"},401);let O=A[_.field];if(!re(O,_.value))return m({error:`Not your ${e}`},403);let J=Object.keys(y).find((H)=>T(H)===T(_.field));if(J!==void 0&&!re(y[J],_.value))return m({error:`Cannot reassign ${e} ownership`},403)}if(t.traits?.useTimestamps!==!1)y.updated_at=new Date().toISOString();let I=await et(y,t),k=ye(tt(I,t));await C.updateTable(i).set(k).where({id:l}).execute();let U={...A,...k};try{let O=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(O)U=O}catch{}return m({data:K(se(U,t),p)})}catch(l){let{status:g,body:b}=me(l,e,"update");return m(b,g)}};if(!G("PUT",`${d}/{id}`))q(L.put(`${d}/{id}`,h),R);if(!G("PATCH",`${d}/{id}`))q(L.patch(`${d}/{id}`,h),R)}let x=!!t.traits?.useSoftDeletes;if(o.includes("destroy")&&!G("DELETE",`${d}/{id}`))q(L.delete(`${d}/{id}`,async(h)=>{try{let a=pe(h.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let g=await Y(h),b=await ee(t,g,h);if(b.enforced&&!b.bypass){if(!g)return m({error:"Auth required"},401);let y=l[b.field];if(!re(y,b.value))return m({error:`Not your ${e}`},403)}if(x){let y=new Date().toISOString();await C.updateTable(i).set({deleted_at:y,updated_at:y}).where({id:a}).execute()}else await C.deleteFrom(i).where({id:a}).execute();return new Response(null,{status:204})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to delete ${e}`,detail:String(a)},500)}}),R);if(o.includes("destroy")&&!G("POST",`${d}/bulk-delete`))q(L.post(`${d}/bulk-delete`,async(h)=>{try{let l=(await je(h))?.ids;if(!Array.isArray(l)||l.length===0)return m({error:"An array of IDs is required"},422);if(l.length>100)return m({error:"Cannot delete more than 100 records at once"},422);let g=[],b=[];for(let A of l){let _=pe(A);if(_!=null)g.push(_);else b.push(A)}if(b.length>0)return m({error:"Invalid IDs in batch",invalid:b},422);let y=await Y(h),w=await ee(t,y,h);if(w.enforced&&!w.bypass){if(!y)return m({error:"Auth required"},401);if(w.value==null)return m({error:"Caller has no ownership identity"},403);let A=await C.selectFrom(i).select(["id",w.field]).execute(),_=new Set(A.filter((k)=>re(k[w.field],w.value)).map((k)=>String(k.id))),I=g.filter((k)=>!_.has(String(k)));if(I.length>0)return m({error:`Cannot delete ${e} you don't own`,ids:I},403)}let B=new Date().toISOString();for(let A of g)if(x)await C.updateTable(i).set({deleted_at:B,updated_at:B}).where({id:A}).execute();else await C.deleteFrom(i).where({id:A}).execute();return m({message:`Successfully deleted ${g.length} ${s}`})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to bulk delete ${s}`,detail:String(a)},500)}}),R)}at=L});var ut={};ae(ut,{default:()=>at});var dt=Z(async()=>{await ct()});class _e{data;status;headers;isOk;constructor(e,t,n,r){this.data=e;this.status=t;this.headers=n;this.isOk=r}ok(){return this.status===200}created(){return this.status===201}accepted(){return this.status===202}noContent(){return this.status===204}movedPermanently(){return this.status===301}found(){return this.status===302}badRequest(){return this.status===400}unauthorized(){return this.status===401}paymentRequired(){return this.status===402}forbidden(){return this.status===403}notFound(){return this.status===404}requestTimeout(){return this.status===408}conflict(){return this.status===409}unprocessableEntity(){return this.status===422}tooManyRequests(){return this.status===429}serverError(){return this.status===500}}class ve{defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams(e){return this.queryParams=e,this}withHeaders(e){return this.customHeaders={...this.customHeaders,...e},this}accept(e){return this.defaultHeaders.Accept=e,this}acceptJson(){return this.accept("application/json")}withToken(e){return this.customHeaders.Authorization=`Bearer ${e}`,this}withBasicAuth(e,t){let n=btoa(`${e}:${t}`);return this.customHeaders.Authorization=`Basic ${n}`,this}withDigestAuth(e,t){return this.digestAuth={username:e,password:t},this}withBody(e){return this.bodyData=e,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach(e,t,n,r){let s=typeof t==="string"?new Blob([t],{type:r?.["Content-Type"]||"text/plain"}):t;return this.attachments.push({name:e,content:s,filename:n,headers:r}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams(e){if(!this.queryParams)return e;let t=new URLSearchParams;Object.entries(this.queryParams).forEach(([s,o])=>{if(o!=null)t.append(s,String(o))});let n=t.toString();if(!n)return e;let r=e.includes("?");return e+(r?"&":"?")+n}async formatBody(e){let t=e||this.bodyData;if(this.isMultipart){let n=new FormData;if(t)Object.entries(t).forEach(([r,s])=>{n.append(r,String(s))});for(let r of this.attachments)if(r.headers){let s=r.content instanceof Blob?new Blob([r.content],{type:r.headers["Content-Type"]}):r.content;n.append(r.name,s,r.filename)}else n.append(r.name,r.content,r.filename);return n}if(this.isFormData&&t){let n=new URLSearchParams;return Object.entries(t).forEach(([r,s])=>{if(s!=null)n.append(r,String(s))}),n.toString()}return t?JSON.stringify(t):void 0}resetState(){this.queryParams=void 0,this.bodyData=void 0,this.isFormData=!1,this.isMultipart=!1,this.customHeaders={},this.attachments=[],this.digestAuth=void 0,this.defaultHeaders["Content-Type"]="application/json"}async handleDigestAuth(e,t,n,r){if(e.status!==401||!this.digestAuth)return e;let s=e.headers.get("WWW-Authenticate");if(!s?.startsWith("Digest "))return e;let o=s.substring(7).split(",").reduce((P,S)=>{let[v,j]=S.trim().split("=");if(v)P[v]=j?.replace(/["']/g,"")??"";return P},{}),i=await this.generateMD5(`${this.digestAuth.username}:${o.realm}:${this.digestAuth.password}`),c=await this.generateMD5(`${n}:${t}`),p="00000001",d=await this.generateMD5(Date.now().toString()).then((P)=>P.substring(0,8)),u=await this.generateMD5(`${i}:${o.nonce}:${p}:${d}:${o.qop}:${c}`),f={username:`"${this.digestAuth.username}"`,realm:`"${o.realm}"`,nonce:`"${o.nonce}"`,uri:`"${t}"`,algorithm:o.algorithm?`"${o.algorithm}"`:void 0,qop:`"${o.qop}"`,nc:p,cnonce:`"${d}"`,response:`"${u}"`,opaque:o.opaque?`"${o.opaque}"`:void 0},R=Object.entries(f).filter(([P,S])=>S!==void 0).map(([P,S])=>`${P}=${S}`).join(", ");return this.customHeaders.Authorization=`Digest ${R}`,fetch(t,{method:n,headers:this.getHeaders(),body:r?this.formatBody(r):void 0})}async generateMD5(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}async request(e,t,n){let r=this.addQueryParams(e),s=await this.formatBody(n),o=await fetch(r,{method:t,headers:this.getHeaders(),body:s});if(this.digestAuth)o=await this.handleDigestAuth(o,r,t,n);let i=await o.json();return this.resetState(),new _e(i,o.status,o.headers,o.ok)}async get(e){return this.request(e,"GET")}async post(e,t){return this.request(e,"POST",t)}async put(e,t){return this.request(e,"PUT",t)}async patch(e,t){return this.request(e,"PATCH",t)}async delete(e){return this.request(e,"DELETE")}}var Kt=new ve;ge();import{path as te}from"@stacksjs/path";function pt(e){if(!e||typeof e!=="object")return{type:"string"};let t=e,n=Array.isArray(t.rules)?t.rules:[],r=(u)=>n.find((f)=>f.name===u),s=(u,f)=>{let R=r(u)?.params?.[f];return typeof R==="number"?R:void 0},o=t.name??t._type??"string",i={type:o==="enum"?"string":o},c=s("min","min")??(typeof t._min==="number"?t._min:void 0),p=s("max","max")??(typeof t._max==="number"?t._max:void 0);if(c!==void 0)i[o==="string"?"minLength":"minimum"]=c;if(p!==void 0)i[o==="string"?"maxLength":"maximum"]=p;if(r("email")||t._email)i.format="email";if(r("url")||t._url)i.format="uri";if(r("uuid")||t._uuid)i.format="uuid";let d=Array.isArray(t.allowedValues)?t.allowedValues:Array.isArray(t._enum)?t._enum:null;if(d)i.enum=d;return i}function Wt(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function lt(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function zt(e){let t={id:{type:"integer"}},n=["id"];if(e.traits?.useUuid)t.uuid={type:"string",format:"uuid"},n.push("uuid");for(let[r,s]of Object.entries(e.attributes??{})){if(s.hidden===!0)continue;let o=lt(r);if(t[o]=pt(s.validation?.rule),s.required===!0)n.push(o)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let s=`${lt(r.trim())}_id`;t[s]??={type:"integer"}}if(e.traits?.useTimestamps!==!1)t.created_at={type:"string",format:"date-time"},t.updated_at={type:"string",format:"date-time"};if(e.traits?.useSoftDeletes)t.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties:t,required:[...new Set(n)]}}function Vt(e){let t=e.traits?.useApi;if(!t||typeof t!=="object"||!t.uri)return null;let n=String(t.prefix||"").replace(/^\/+|\/+$/g,""),r=String(t.uri).replace(/^\/+|\/+$/g,"");return`/api/${n?`${n}/`:""}${r}`}function Qt(e,t){let n={...t},r=e?.responses;if(r&&typeof r==="object")for(let[o,i]of Object.entries(r)){let c=i;if(!c||typeof c!=="object"||typeof c.description!=="string")continue;n[String(o)]={description:c.description,...c.schema&&typeof c.schema==="object"?{content:{"application/json":{schema:c.schema}}}:{}}}let s=e?.responseHeaders;if(s&&typeof s==="object"){let o={};for(let[i,c]of Object.entries(s)){let p=c;if(!p||typeof p!=="object"||typeof p.description!=="string")continue;o[i]={description:p.description,...p.schema&&typeof p.schema==="object"?{schema:p.schema}:{}}}if(Object.keys(o).length>0)for(let i of Object.keys(n))n[i]={...n[i],headers:o}}return n}async function Gt(e){if(typeof e!=="string"||!e||e.includes(".."))return null;try{let{path:t}=await import("@stacksjs/path"),n=[t.appPath(`${e}.ts`),t.storagePath(`framework/defaults/app/${e}.ts`)];for(let r of n)try{if(!await Bun.file(r).exists())continue;let i=(await import(r)).default;return i&&typeof i==="object"?i:null}catch{}}catch{}return null}async function mn(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router");try{let{loadRoutes:u}=await import("@stacksjs/router"),{default:f}=await import(te.appPath("Routes.ts"));await u(f)}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${f}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${f}`)}try{try{await import("@stacksjs/orm/routes")}catch{await dt().then(() => ut)}}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${f}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${f}`)}let r={};try{let f;try{f=await import("@stacksjs/orm/model-registry")}catch{f=await Promise.resolve().then(() => (Ae(),Ge))}r=await f.loadModelRegistry({defaultsRoot:te.storagePath("framework/defaults/app/Models"),userRoot:te.projectPath("app/Models")})}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${f}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${f}`)}let s=(u)=>u.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),o=[...n()].map((u)=>({route:u,oasPath:s(u.path),method:u.method.toLowerCase()})).sort((u,f)=>{if(u.oasPath!==f.oasPath)return u.oasPath<f.oasPath?-1:1;return u.method<f.method?-1:u.method>f.method?1:0});if(t&&o.length===0)throw Error("[generateOpenApi] Refusing to emit an empty spec: no routes were registered. This usually means route loading failed silently rather than that the app has no API.");let i="Stacks API";if(!t)try{let{config:u}=await import("@stacksjs/config");if(u.app?.name)i=`${u.app.name} API`}catch{}let c={openapi:"3.0.0",info:{title:i,version:"1.0.0"},paths:{},components:{schemas:{}}},p=Object.values(r).map((u)=>({name:String(u.name),path:Vt(u),schema:zt(u)})).filter((u)=>u.path!==null).sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);for(let u of p)c.components.schemas[u.name]=u.schema;let d=new Set;for(let{route:u,oasPath:f,method:R}of o){if(!c.paths[f])c.paths[f]={};let P=[];for(let a of u.path.matchAll(/\{(\w+)\}/g))if(a[1])P.push(a[1]);for(let a of u.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(a[1])P.push(a[1]);let S=u.name??`${R}_${f.replace(/[^a-z0-9]/gi,"_")}`,v=S;if(d.has(v)){v=`${S}_${R}`;let a=2;while(d.has(v))v=`${S}_${R}_${a++}`}d.add(v);let j={summary:u.name??u.path,operationId:v,parameters:P.map((a)=>({name:a,in:"path",required:!0,schema:{type:"string"}})),responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object"}}}},422:{description:"Validation failed"},500:{description:"Server error"}}},E=p.find((a)=>f===a.path||f===`${a.path}/{id}`);if(E){let a=f===E.path&&R==="get"?{type:"array",items:E.schema}:E.schema;if(j.responses[200].content={"application/json":{schema:{type:"object",properties:{data:a},required:["data"]}}},R==="post"&&f===E.path)j.responses[201]={...j.responses[200],description:"Created"},delete j.responses[200]}let q=u.action??(u.handler?await Gt(u.handler):null),x=q&&typeof q.validations==="object"&&q.validations!==null?q.validations:null;j.responses=Qt(q,j.responses);let h=q?.requestHeaders;if(h&&typeof h==="object")for(let[a,l]of Object.entries(h)){let g=l;if(!g||typeof g!=="object"||typeof g.description!=="string")continue;j.parameters?.push({name:a,in:"header",description:g.description,required:g.required===!0,schema:g.schema&&typeof g.schema==="object"?g.schema:{type:"string"}})}if(x&&Object.keys(x).length>0){let a=Object.entries(x).map(([l,g])=>{let b=g?.rule;return{field:l,schema:pt(b),required:Wt(b)}});if(R==="get"||R==="head"||R==="delete"){let l=new Set(P);for(let{field:g,schema:b,required:y}of a){if(l.has(g))continue;j.parameters?.push({name:g,in:"query",required:y,schema:b})}}else{let l={type:"object",properties:{},required:[]},g=l.properties,b=l.required;for(let y of a)if(g[y.field]=y.schema,y.required)b.push(y.field);if(b.length===0)delete l.required;j.requestBody={required:b.length>0,content:{"application/json":{schema:l}}}}}c.paths[f][R]=j}if(e.write!==!1){await Bun.write(te.frameworkPath("api/openapi.json"),JSON.stringify(c,null,2));let{renderOpenApiTypes:u}=await Promise.resolve().then(() => (ce(),De)),{renderApiClient:f}=await Promise.resolve().then(() => (ge(),Ce));await Bun.write(te.frameworkPath("api/api-types.ts"),u(c)),await Bun.write(te.frameworkPath("api/client.ts"),f(c,{name:c.info.title}))}return c}ce();class F{static instance=new F;isMissing(){return!0}}class oe{data;constructor(e){this.data=e}}class ft{condition;value;defaultValue;constructor(e,t,n=new F){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class gt{resource;additional={};request;static wrap="data";static additionalMeta={};constructor(e){this.resource=e}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=this.toArray(e||this.request);return this.filterAndResolve(t)}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{...t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}toJSON(){return this.toResponse()}static collection(e){return new xe(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:F.instance}whenNotNull(e,t){if(e===null||e===void 0)return F.instance;return t?t(e):e}whenLoaded(e,t,n){let r=this.resource;if(!((e in r)&&r[e]!==void 0))return n!==void 0?n:F.instance;if(t!==void 0)return typeof t==="function"?t():t;return r[e]}whenCounted(e,t){let n=this.resource,r=`${e}_count`;if(r in n)return n[r];return t!==void 0?t:F.instance}merge(e){return new oe(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return F.instance;let r=typeof t==="function"?t():t;return new oe(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=gt.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof F)continue;if(s instanceof oe){Object.assign(n,this.filterAndResolve(s.data,t+1));continue}if(s instanceof ft){let o=s.resolve();if(!(o instanceof F))n[r]=o;continue}if(s!==null&&typeof s==="object"&&!Array.isArray(s)&&!(s instanceof Date)){n[r]=this.filterAndResolve(s,t+1);continue}if(Array.isArray(s)){n[r]=s.filter((o)=>!(o instanceof F)).map((o)=>{if(o instanceof oe)return o.data;if(o!==null&&typeof o==="object"&&!(o instanceof Date))return this.filterAndResolve(o,t+1);return o});continue}n[r]=s}return n}static withoutWrapping(){this.wrap=null}static wrapWith(e){this.wrap=e}}class xe{resources;ResourceClass;additional={};request;static wrap="data";constructor(e,t){this.resources=e,this.ResourceClass=t}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=e||this.request;return this.resources.map((n)=>{let r=new this.ResourceClass(n);if(t)r.withRequest(t);return r.resolve(t)})}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{data:t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class ht extends xe{meta;links;constructor(e,t){super(e.data,t);this.meta=e.meta,this.links=e.links}static fromPagination(e,t,n){let{currentPage:r,perPage:s,total:o,baseUrl:i=""}=n,c=Math.ceil(o/s),p=o>0?(r-1)*s+1:null,d=o>0?Math.min(r*s,o):null;return new ht({data:e,meta:{current_page:r,from:p,last_page:c,per_page:s,to:d,total:o},links:{first:`${i}?page=1`,last:`${i}?page=${c}`,prev:r>1?`${i}?page=${r-1}`:null,next:r<c?`${i}?page=${r+1}`:null}},t)}toResponse(e){return{data:this.resolve(e),meta:this.meta,links:this.links,...this.additional}}}function bn(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function wn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{ft as ConditionalValue,gt as JsonResource,oe as MergeValue,F as MissingValue,ht as PaginatedResourceCollection,xe as ResourceCollection,wn as collection,Qt as describedResponses,Kt as fetcher,mn as generateOpenApi,Ne as methodName,zt as modelDefinitionToSchema,_t as renderApiClient,At as renderOpenApiTypes,bn as resource,Wt as ruleIsRequired,pt as ruleToSchema,M as schemaType};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/api",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.72.56",
5
+ "version": "0.72.60",
6
6
  "description": "The Stacks API utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -62,6 +62,6 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "better-dx": "^0.2.24",
65
- "@stacksjs/utils": "0.72.56"
65
+ "@stacksjs/utils": "0.72.60"
66
66
  }
67
67
  }