@stacksjs/api 0.72.63 → 0.72.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +10 -10
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var bt=Object.defineProperty;var
|
|
2
|
+
var bt=Object.defineProperty;var Rt=(e)=>e;function Ot(e,t){this[e]=Rt.bind(null,t)}var ce=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Ot.bind(t,n)})};var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=import.meta.require;var qe={};ce(qe,{renderOpenApiTypes:()=>Tt,schemaType:()=>M});function kt(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(kt).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 $t(e=[]){return` parameters: {
|
|
3
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
|
|
6
|
-
requestBody${e.requestBody.required?"":"?"}: { content: ${
|
|
7
|
-
requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${
|
|
8
|
-
${
|
|
5
|
+
}`}function ve(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${M(n.schema)}`).join("; ")} }`}function At(e){let t=e.requestBody?`
|
|
6
|
+
requestBody${e.requestBody.required?"":"?"}: { content: ${ve(e.requestBody.content)} }`:`
|
|
7
|
+
requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${ve(s.content)} }`);return`{
|
|
8
|
+
${$t(e.parameters)}${t}
|
|
9
9
|
responses: {
|
|
10
10
|
${n.join(`
|
|
11
11
|
`)}
|
|
12
12
|
}
|
|
13
|
-
}`}function
|
|
13
|
+
}`}function Tt(e){let t=Object.entries(e.paths||{}).map(([r,s])=>{let o=St.map((i)=>{let c=s[i];return c?` ${i}: ${At(c)}`:` ${i}?: never`});return` ${JSON.stringify(r)}: {
|
|
14
14
|
${o.join(`
|
|
15
15
|
`)}
|
|
16
16
|
}`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${M(s)}`);return`/**
|
|
@@ -29,13 +29,13 @@ ${n.join(`
|
|
|
29
29
|
`)}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}var
|
|
32
|
+
`}var St;var ue=Z(()=>{St=["get","put","post","delete","options","head","patch","trace"]});var Ne={};ce(Ne,{methodName:()=>De,renderApiClient:()=>vt});function De(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 xt(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 Pt(e,t=" "){let n=e.filter(Boolean);if(!n.length)return"";return`${t}/**
|
|
33
33
|
${n.map((r)=>`${t} * ${r}`).join(`
|
|
34
34
|
`)}
|
|
35
35
|
${t} */
|
|
36
|
-
`}function
|
|
36
|
+
`}function _t(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`${Pt([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${f}options?: RequestOptions): Promise<ApiResult<${xt(n)}>> {
|
|
37
37
|
return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${d.length?"input ?? {}":"{}"}, ${R}, ${c?"true":"false"}, options)
|
|
38
|
-
},`}function
|
|
38
|
+
},`}function vt(e,t={}){let n=t.name??"API",r=new Map,s=[];for(let[o,i]of Object.entries(e.paths??{}))for(let c of jt){let p=i[c];if(!p)continue;let d=De(p.operationId??`${c}_${o}`),u=r.get(d)??0;r.set(d,u+1),s.push(_t(o,c,p,u===0?d:`${d}${u+1}`))}return`/* eslint-disable */
|
|
39
39
|
/**
|
|
40
40
|
* ${n} client, generated from the OpenAPI document.
|
|
41
41
|
*
|
|
@@ -136,4 +136,4 @@ ${s.join(`
|
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
export type Client = ReturnType<typeof createClient>
|
|
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};
|
|
139
|
+
`}var jt;var ge=Z(()=>{ue();jt=["get","put","post","delete","options","head","patch"]});function qt(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(qt(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 we(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 Dt(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 be(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??{}),...Nt]){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 It(e){try{return JSON.parse(e)}catch{return e}}function Et(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"?Ct[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=Dt(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 He(e,t,n){let r=Ce(n);return e.find((s)=>s.method===t&&Ce(String(s.path??""))===r)}function Ce(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 Le(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 We(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,Bt);return{page:n,perPage:s,offset:(n-1)*s}}function de(e,t){let n=new URL(e.toString());return n.searchParams.set("page",String(t)),`${n.pathname}${n.search}`}function le(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?de(e,t-1):null,next_page_url:s?de(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=de(e,1),p.last_page_url=de(e,d)}return p}function Se(e,t,n,r,s,o){let{page:i,...c}=le(e,t,n,r,s,o);return{current_page:i,...c}}var Nt,Ct,Ie=15,Bt=100;var ze=Z(()=>{Nt=["id","uuid","created_at","updated_at","deleted_at"];Ct={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"?It(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"?Et(e):[],set:(e)=>e==null?null:Array.isArray(e)?JSON.stringify(e):e}}});var Xe={};ce(Xe,{loadModelRegistry:()=>ke,modelFiles:()=>Ge});import{readdirSync as Mt}from"fs";import{basename as Ft,extname as Qe,join as Ut}from"path";function Ge(e){let t=[],n=(r)=>{let s;try{s=Mt(r,{withFileTypes:!0})}catch{return}for(let o of s){let i=Ut(r,o.name);if(o.isDirectory()){n(i);continue}if(![".ts",".js"].includes(Qe(o.name)))continue;if(o.name.startsWith(".")||o.name.startsWith("index"))continue;t.push(i)}};return n(e),t.sort()}async function Ve(e,t,n){for(let r of Ge(e))try{let s=Qe(r),o=await import(`${r}?t=${Date.now()}`),i=o.default??o,c=i.name??Ft(r,s);t[c]={...i,name:c}}catch(s){n?.(r,s)}}async function ke(e){let t={};return await Ve(e.defaultsRoot,t,e.onImportError),await Ve(e.userRoot,t,e.onImportError),t}var $e=()=>{};import{route as L}from"@stacksjs/router";import{env as Q}from"@stacksjs/env";import{projectPath as st,storagePath as Jt}from"@stacksjs/path";import{createQueryBuilder as Ht,defaultConfig as Ze,setConfig as Ke}from"@stacksjs/query-builder";import{HttpError as z}from"@stacksjs/error-handling";import{log as oe}from"@stacksjs/logging";function G(e,t){let n=He(L.routes,e,t);if(!n)return!1;let r=String(n.path??"");return oe.info(`[orm] Skipping generated ${e} ${t} - already defined${r&&r!==t?` as ${r}`:""}.`),!0}function ot(e){if(!e.attributes)return[];return Object.entries(e.attributes).filter(([t,n])=>n.hidden===!0).map(([t])=>t)}function Ye(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 et(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(Ye(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||Ye(T(u.modelName)),P=ot(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 tt(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 nt(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 Te(e){if(Number(e.headers?.get?.("content-length")??0)>pe)throw new z(413,`Request body exceeds ${pe}-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>pe)throw new z(413,`Request body exceeds ${pe}-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 fe(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 it(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=it(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 Wt(e){let t=it(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 at(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(Wt(r))}}}async function ee(e,t,n){let r=at(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 rt(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 Lt,Ae,C,pe=1048576,ct;var ut=Z(async()=>{ze();$e();Lt=st("config/qb.ts");try{let e=(await import(Lt)).default;Ke(e??Ze)}catch{oe.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let e=Q.DB_CONNECTION||"sqlite";Ke({...Ze,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||""}})}Ae=await ke({defaultsRoot:Jt("framework/defaults/app/Models"),userRoot:st("app/Models"),onImportError:(e,t)=>oe.warn(`[orm] Could not load model ${e}: ${t.message}`)}),C=Ht();for(let[e,t]of Object.entries(Ae)){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=ot(t),d=Ee(s,r.prefix),u=Ue(t.attributes,p),{read:f,write:R,declared:P}=Le(n);if(["store","update","destroy"].some((h)=>o.includes(h))&&P&&R.length===0)oe.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)oe.debug(`[orm] ${e}: registering public read routes at ${d} (declared \`middleware.read: []\`)`);let j=!!at(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:w}=We(a.searchParams),y=a.searchParams.get("sort"),b=C.selectFrom(i);b=Je(b,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)b=b.where(V,"=",N)}let A=a.searchParams.get("search");if(A&&c.length>0){let D=c.slice(0,5);b=b.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)b=b.select(D)}let I=!!t.traits?.useSoftDeletes,k=a.searchParams.get("withTrashed")==="true",U=a.searchParams.get("onlyTrashed")==="true";if(I&&!k)b=U?b.whereNotNull("deleted_at"):b.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=Se(a,l,g,0,!1,void 0);return new Response(JSON.stringify({data:[],...D,meta:le(a,l,g,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}b=Array.isArray(O.value)?b.where(O.field,"in",O.value):b.where(O.field,"=",O.value)}let J=await b.limit(g+1).offset(w).get()||[],H=J.length>g,ne=(H?J.slice(0,g):J).map((D)=>K(se(D,t),p)),xe=a.searchParams.get("include");if(xe)ne=await et(ne,t,xe,Ae);let yt=a.searchParams.get("with_count")==="true",X;if(yt)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 ae={"Content-Type":"application/json"};if(X!==void 0&&!Number.isNaN(X))ae["X-Total-Count"]=String(X);ae["Cache-Control"]=O.enforced&&!O.bypass?"private, no-store":"public, max-age=15, must-revalidate",ae.Vary="Authorization";let wt=Se(a,l,g,ne.length,H,X);return new Response(JSON.stringify({data:ne,...wt,meta:le(a,l,g,ne.length,H,X)}),{status:200,headers:ae})}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=fe(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 w=j?await ee(t,await Y(h),h):{enforced:!1,value:null,field:"",bypass:!1};if(w.enforced&&!w.bypass){if(w.value==null||!re(l[w.field],w.value))return m({error:`${e} not found`},404)}let y=K(se(l,t),p),b=g.searchParams.get("include");if(b){let[k]=await et([y],t,b,Ae);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"]=w.enforced&&!w.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 Te(h),l=be(a,p),g=we(l,c),w=await Y(h);if(w){let k=await rt(t,"creating",w,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,w,h);if(y.enforced&&!y.bypass){if(!w)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 b=Oe(g,t,"creating");if(!b.valid)return m({success:!1,message:"Validation failed",errors:b.errors},422);if(t.traits?.useTimestamps!==!1){let k=new Date().toISOString();g.created_at=k,g.updated_at=k}let B=await tt(g,t),A=ye(nt(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=fe(a.params?.id);if(l==null)return m({error:"Invalid ID parameter"},400);let g=await Te(a),w=be(g,p),y=we(w,c),b=await Y(a);if(b){let O=await rt(t,"updating",b,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,b,a);if(_.enforced&&!_.bypass){if(!b)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 tt(y,t),k=ye(nt(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:w}=me(l,e,"update");return m(w,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=fe(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),w=await ee(t,g,h);if(w.enforced&&!w.bypass){if(!g)return m({error:"Auth required"},401);let y=l[w.field];if(!re(y,w.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 Te(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=[],w=[];for(let A of l){let _=fe(A);if(_!=null)g.push(_);else w.push(A)}if(w.length>0)return m({error:"Invalid IDs in batch",invalid:w},422);let y=await Y(h),b=await ee(t,y,h);if(b.enforced&&!b.bypass){if(!y)return m({error:"Auth required"},401);if(b.value==null)return m({error:"Caller has no ownership identity"},403);let A=await C.selectFrom(i).select(["id",b.field]).execute(),_=new Set(A.filter((k)=>re(k[b.field],b.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)}ct=L});var dt={};ce(dt,{default:()=>ct});var lt=Z(async()=>{await ut()});class Pe{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 _e{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 Pe(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 Yt=new _e;ge();import{path as te}from"@stacksjs/path";function ft(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 zt(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function pt(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Vt(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=pt(r);if(t[o]=ft(s.validation?.rule),s.required===!0)n.push(o)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let s=`${pt(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 Qt(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 Gt(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 Xt(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 yn(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 lt().then(() => dt)}}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(() => ($e(),Xe))}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:Qt(u),schema:Vt(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 Xt(u.handler):null),x=q&&typeof q.validations==="object"&&q.validations!==null?q.validations:null;j.responses=Gt(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 w=g?.rule;return{field:l,schema:ft(w),required:zt(w)}});if(R==="get"||R==="head"||R==="delete"){let l=new Set(P);for(let{field:g,schema:w,required:y}of a){if(l.has(g))continue;j.parameters?.push({name:g,in:"query",required:y,schema:w})}}else{let l={type:"object",properties:{},required:[]},g=l.properties,w=l.required;for(let y of a)if(g[y.field]=y.schema,y.required)w.push(y.field);if(w.length===0)delete l.required;j.requestBody={required:w.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(() => (ue(),qe)),{renderApiClient:f}=await Promise.resolve().then(() => (ge(),Ne));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}ue();class F{static instance=new F;isMissing(){return!0}}class ie{data;constructor(e){this.data=e}}class gt{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 ht{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 je(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 ie(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return F.instance;let r=typeof t==="function"?t():t;return new ie(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=ht.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof F)continue;if(s instanceof ie){Object.assign(n,this.filterAndResolve(s.data,t+1));continue}if(s instanceof gt){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 ie)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 je{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 mt extends je{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 mt({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 Rn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{gt as ConditionalValue,ht as JsonResource,ie as MergeValue,F as MissingValue,mt as PaginatedResourceCollection,je as ResourceCollection,Rn as collection,Gt as describedResponses,Yt as fetcher,yn as generateOpenApi,De as methodName,Vt as modelDefinitionToSchema,vt as renderApiClient,Tt as renderOpenApiTypes,bn as resource,zt as ruleIsRequired,ft 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.
|
|
5
|
+
"version": "0.72.64",
|
|
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.
|
|
65
|
+
"@stacksjs/utils": "0.72.64"
|
|
66
66
|
}
|
|
67
67
|
}
|