@stacksjs/api 0.73.3 → 0.74.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +13 -13
- package/package.json +8 -3
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
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?"":"?"}: ${
|
|
2
|
+
var At=Object.defineProperty;var Tt=(e)=>e;function _t(e,t){this[e]=Tt.bind(null,t)}var de=(e,t)=>{for(var n in t)At(e,n,{get:t[n],enumerable:!0,configurable:!0,set:_t.bind(t,n)})};var Y=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=import.meta.require;var Ie={};de(Ie,{renderOpenApiTypes:()=>vt,schemaType:()=>U});function Pt(e){return typeof e==="string"?JSON.stringify(e):String(e)}function U(e){if(!e)return"unknown";if(e.enum?.length)return e.enum.map(Pt).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<${U(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)?"":"?"}: ${U(s)}`);if(e.additionalProperties){let r=e.additionalProperties===!0?"unknown":U(e.additionalProperties);n.push(`[key: string]: ${r}`)}return n.length?`{ ${n.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function jt(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?"":"?"}: ${U(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 Ce(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${U(n.schema)}`).join("; ")} }`}function Dt(e){let t=e.requestBody?`
|
|
6
|
+
requestBody${e.requestBody.required?"":"?"}: { content: ${Ce(e.requestBody.content)} }`:`
|
|
7
|
+
requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${Ce(s.content)} }`);return`{
|
|
8
|
+
${jt(e.parameters)}${t}
|
|
9
9
|
responses: {
|
|
10
10
|
${n.join(`
|
|
11
11
|
`)}
|
|
12
12
|
}
|
|
13
|
-
}`}function
|
|
13
|
+
}`}function vt(e){let t=Object.entries(e.paths||{}).map(([r,s])=>{let o=xt.map((i)=>{let c=s[i];return c?` ${i}: ${Dt(c)}`:` ${i}?: never`});return` ${JSON.stringify(r)}: {
|
|
14
14
|
${o.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${
|
|
16
|
+
}`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${U(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
|
*/
|
|
@@ -29,13 +29,13 @@ ${n.join(`
|
|
|
29
29
|
`)}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}var
|
|
32
|
+
`}var xt;var le=Y(()=>{xt=["get","put","post","delete","options","head","patch","trace"]});var Be={};de(Be,{methodName:()=>Ee,renderApiClient:()=>Et});function Ee(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 Nt(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?U(s.schema):"unknown"}function Ct(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
|
|
37
|
-
return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${d.length?"input ?? {}":"{}"}, ${
|
|
38
|
-
},`}function
|
|
36
|
+
`}function It(e,t,n,r){let s=n.parameters??[],o=s.filter((k)=>k.in==="path"),i=s.filter((k)=>k.in==="query"),c=n.requestBody?.content?.["application/json"]?.schema,p=Boolean(n.requestBody?.required),d=[];for(let k of[...o,...i]){let q=k.in==="path"||k.required;d.push(`${JSON.stringify(k.name)}${q?"":"?"}: ${U(k.schema)}`)}if(c)d.push(`body${p?"":"?"}: ${U(c)}`);let u=[...o,...i].every((k)=>k.in!=="path"&&!k.required)&&(!c||!p),f=d.length?`input${u?"?":""}: { ${d.join("; ")} }, `:"",w=i.length?`[${i.map((k)=>JSON.stringify(k.name)).join(", ")}]`:"[]";return`${Ct([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${f}options?: RequestOptions): Promise<ApiResult<${Nt(n)}>> {
|
|
37
|
+
return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${d.length?"input ?? {}":"{}"}, ${w}, ${c?"true":"false"}, options)
|
|
38
|
+
},`}function Et(e,t={}){let n=t.name??"API",r=new Map,s=[];for(let[o,i]of Object.entries(e.paths??{}))for(let c of qt){let p=i[c];if(!p)continue;let d=Ee(p.operationId??`${c}_${o}`),u=r.get(d)??0;r.set(d,u+1),s.push(It(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 jt;var ge=Z(()=>{ue();jt=["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 he(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 Fe(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 Me(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 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 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 ke(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((_)=>i?.validation?.message?.[_?.code]??_?.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 me(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?me(s.read):["auth"],write:"write"in s?me(s.write):["auth"],declared:!0}}let r=me(n);return{read:r,write:r,declared:!0}}function Qe(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 Oe(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 We=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:()=>Se,modelFiles:()=>Ge});import{readdirSync as Ft}from"fs";import{basename as Mt,extname as Ve,join as Ut}from"path";function Ge(e){let t=[],n=(r)=>{let s;try{s=Ft(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(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 Ge(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 Se(e){let t={};return await ze(e.defaultsRoot,t,e.onImportError),await ze(e.userRoot,t,e.onImportError),t}var $e=()=>{};import{route as L}from"@stacksjs/router";import{env as V}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 W}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)),_=ot(f),O=(D)=>K(se(D,f),_);if(u.kind==="belongsTo"||u.kind==="hasOne"){let D=`${T(u.modelName)}_id`,j=[...new Set(e.map((x)=>x[D]).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(),v=new Map;for(let x of E??[])v.set(String(x.id),O(x));for(let x of e)x[d]=v.get(String(x[D]))??null}else{let D=String(t.name??""),j=`${T(D)}_id`,E=[...new Set(e.map((m)=>m.id).filter((m)=>m!=null))];if(!E.length){for(let m of e)m[d]=[];continue}let v=await C.selectFrom(R).whereIn(j,E).get(),x=new Map;for(let m of v??[]){let a=String(m[j]),l=x.get(a)??[];l.push(O(m)),x.set(a,l)}for(let m of e)m[d]=x.get(String(m.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 h(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 W(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 W(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 W)throw n;throw new W(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,Qt,C,pe=1048576,ct;var ut=Z(async()=>{We();$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=V.DB_CONNECTION||"sqlite";Ke({...Ze,dialect:e,database:e==="sqlite"?{database:V.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:V.DB_DATABASE||"stacks",host:V.DB_HOST||"127.0.0.1",port:V.DB_PORT||(e==="postgres"?5432:3306),username:V.DB_USERNAME||(e==="postgres"?"postgres":"root"),password:V.DB_PASSWORD||""}})}Ae=await Se({defaultsRoot:Jt("framework/defaults/app/Models"),userRoot:st("app/Models"),onImportError:(e,t)=>oe.warn(`[orm] Could not load model ${e}: ${t.message}`)}),Qt=Ht(),C=Qt;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=Me(t),p=ot(t),d=Ee(s,r.prefix),u=Ue(t.attributes,p),{read:f,write:R,declared:_}=Le(n);if(["store","update","destroy"].some((m)=>o.includes(m))&&_&&R.length===0)oe.warn(`[orm] ${e}: registering UNAUTHENTICATED mutating routes at ${d} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((m)=>o.includes(m))&&_&&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,v=(m,a=E)=>{let l=m;for(let g of a)if(l&&typeof l.middleware==="function")l=l.middleware(g);return l};if(o.includes("index")&&!G("GET",d))v(L.get(d,async(m)=>{try{let a=new URL(m.url),{page:l,perPage:g,offset:w}=Qe(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[q,N]of a.searchParams.entries()){if(B.has(q)||!N)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(q))continue;let z=u.get(q);if(z)b=b.where(z,"=",N)}let A=a.searchParams.get("search");if(A&&c.length>0){let q=c.slice(0,5);b=b.where((N)=>{for(let z of q)N=N.orWhere(T(z),"like",`%${A}%`);return N})}let P=a.searchParams.get("fields");if(P){let q=P.split(",").map((N)=>N.trim()).filter((N)=>/^[a-z_][a-z0-9_]*$/i.test(N)).map((N)=>T(N));if(q.length>0)b=b.select(q)}let I=!!t.traits?.useSoftDeletes,S=a.searchParams.get("withTrashed")==="true",U=a.searchParams.get("onlyTrashed")==="true";if(I&&!S)b=U?b.whereNotNull("deleted_at"):b.whereNull("deleted_at");let k=j?await ee(t,await Y(m),m):{enforced:!1,value:null,field:"",bypass:!1};if(k.enforced&&!k.bypass){if(k.value==null||Array.isArray(k.value)&&k.value.length===0){let q=Oe(a,l,g,0,!1,void 0);return new Response(JSON.stringify({data:[],...q,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(k.value)?b.where(k.field,"in",k.value):b.where(k.field,"=",k.value)}let J=await b.limit(g+1).offset(w).get()||[],H=J.length>g,ne=(H?J.slice(0,g):J).map((q)=>K(se(q,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 q=C.selectFrom(i);if(k.enforced&&!k.bypass&&k.value!=null)q=Array.isArray(k.value)?q.where(k.field,"in",k.value):q.where(k.field,"=",k.value);let N=await q.count(),z=typeof N==="number"?N:Number(N?.count??N);if(Number.isFinite(z))X=z}catch{}let ae={"Content-Type":"application/json"};if(X!==void 0&&!Number.isNaN(X))ae["X-Total-Count"]=String(X);ae["Cache-Control"]=k.enforced&&!k.bypass?"private, no-store":"public, max-age=15, must-revalidate",ae.Vary="Authorization";let wt=Oe(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 W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to fetch ${s}`,detail:String(a)},500)}}));if(o.includes("show")&&!G("GET",`${d}/{id}`))v(L.get(`${d}/{id}`,async(m)=>{try{let a=fe(m.params?.id);if(a==null)return h({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return h({error:`${e} not found`},404);let g=new URL(m.url);if(t.traits?.useSoftDeletes&&l.deleted_at&&g.searchParams.get("withTrashed")!=="true")return h({error:`${e} not found`},404);let w=j?await ee(t,await Y(m),m):{enforced:!1,value:null,field:"",bypass:!1};if(w.enforced&&!w.bypass){if(w.value==null||!re(l[w.field],w.value))return h({error:`${e} not found`},404)}let y=K(se(l,t),p),b=g.searchParams.get("include");if(b){let[S]=await et([y],t,b,Ae);y=S}let B=y?.updated_at||y?.created_at,A=B?`W/"${y.id}-${String(B)}"`:void 0,P=m.headers?.get?.("if-none-match");if(A&&P&&P===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 W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to fetch ${e}`,detail:String(a)},500)}}));if(o.includes("store")&&!G("POST",d))v(L.post(d,async(m)=>{try{let a=await Te(m),l=be(a,p),g=we(l,c),w=await Y(m);if(w){let S=await rt(t,"creating",w,m);for(let[U,k]of Object.entries(S))if(k!==void 0&&k!==null&&g[U]===void 0)g[U]=k}let y=await ee(t,w,m);if(y.enforced&&!y.bypass){if(!w)return h({error:"Auth required"},401);let S=Fe(g,y.field,y.value);if(S.error)return h({error:S.error},403);g=S.data}if(Object.keys(g).length===0)return h({error:"No fillable fields provided"},422);let b=ke(g,t,"creating");if(!b.valid)return h({success:!1,message:"Validation failed",errors:b.errors},422);if(t.traits?.useTimestamps!==!1){let S=new Date().toISOString();g.created_at=S,g.updated_at=S}let B=await tt(g,t),A=ye(nt(B,t)),P=await C.insertInto(i).values(A).execute(),I=A;try{let S=P?.lastInsertRowid??P?.insertId??P;if(S){let U=await C.selectFrom(i).where({id:S}).executeTakeFirst();if(U)I=U}}catch{}return h({data:K(se(I,t),p)},201)}catch(a){let{status:l,body:g}=he(a,e,"create");return h(g,l)}}),R);if(o.includes("update")){let m=async(a)=>{try{let l=fe(a.params?.id);if(l==null)return h({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 k=await rt(t,"updating",b,a);for(let[J,H]of Object.entries(k))if(H!==void 0&&H!==null&&y[J]===void 0)y[J]=H}if(Object.keys(y).length===0)return h({error:"No fillable fields provided"},422);let B=ke(y,t,"updating");if(!B.valid)return h({success:!1,message:"Validation failed",errors:B.errors},422);let A=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(!A)return h({error:`${e} not found`},404);let P=await ee(t,b,a);if(P.enforced&&!P.bypass){if(!b)return h({error:"Auth required"},401);let k=A[P.field];if(!re(k,P.value))return h({error:`Not your ${e}`},403);let J=Object.keys(y).find((H)=>T(H)===T(P.field));if(J!==void 0&&!re(y[J],P.value))return h({error:`Cannot reassign ${e} ownership`},403)}if(t.traits?.useTimestamps!==!1)y.updated_at=new Date().toISOString();let I=await tt(y,t),S=ye(nt(I,t));await C.updateTable(i).set(S).where({id:l}).execute();let U={...A,...S};try{let k=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(k)U=k}catch{}return h({data:K(se(U,t),p)})}catch(l){let{status:g,body:w}=he(l,e,"update");return h(w,g)}};if(!G("PUT",`${d}/{id}`))v(L.put(`${d}/{id}`,m),R);if(!G("PATCH",`${d}/{id}`))v(L.patch(`${d}/{id}`,m),R)}let x=!!t.traits?.useSoftDeletes;if(o.includes("destroy")&&!G("DELETE",`${d}/{id}`))v(L.delete(`${d}/{id}`,async(m)=>{try{let a=fe(m.params?.id);if(a==null)return h({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return h({error:`${e} not found`},404);let g=await Y(m),w=await ee(t,g,m);if(w.enforced&&!w.bypass){if(!g)return h({error:"Auth required"},401);let y=l[w.field];if(!re(y,w.value))return h({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 W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to delete ${e}`,detail:String(a)},500)}}),R);if(o.includes("destroy")&&!G("POST",`${d}/bulk-delete`))v(L.post(`${d}/bulk-delete`,async(m)=>{try{let l=(await Te(m))?.ids;if(!Array.isArray(l)||l.length===0)return h({error:"An array of IDs is required"},422);if(l.length>100)return h({error:"Cannot delete more than 100 records at once"},422);let g=[],w=[];for(let A of l){let P=fe(A);if(P!=null)g.push(P);else w.push(A)}if(w.length>0)return h({error:"Invalid IDs in batch",invalid:w},422);let y=await Y(m),b=await ee(t,y,m);if(b.enforced&&!b.bypass){if(!y)return h({error:"Auth required"},401);if(b.value==null)return h({error:"Caller has no ownership identity"},403);let A=await C.selectFrom(i).select(["id",b.field]).execute(),P=new Set(A.filter((S)=>re(S[b.field],b.value)).map((S)=>String(S.id))),I=g.filter((S)=>!P.has(String(S)));if(I.length>0)return h({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 h({message:`Successfully deleted ${g.length} ${s}`})}catch(a){if(a instanceof W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({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 _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 Pe{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((_,O)=>{let[D,j]=O.trim().split("=");if(D)_[D]=j?.replace(/["']/g,"")??"";return _},{}),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((_)=>_.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(([_,O])=>O!==void 0).map(([_,O])=>`${_}=${O}`).join(", ");return this.customHeaders.Authorization=`Digest ${R}`,fetch(t,{method:n,headers:this.getHeaders(),body:r?await 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 en=new Pe;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 Gt(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 Xt(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 Zt(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 wn(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:Gt(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 _=[];for(let a of u.path.matchAll(/\{(\w+)\}/g))if(a[1])_.push(a[1]);for(let a of u.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(a[1])_.push(a[1]);let O=u.name??`${R}_${f.replace(/[^a-z0-9]/gi,"_")}`,D=O;if(d.has(D)){D=`${O}_${R}`;let a=2;while(d.has(D))D=`${O}_${R}_${a++}`}d.add(D);let j={summary:u.name??u.path,operationId:D,parameters:_.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 v=u.action??(u.handler?await Zt(u.handler):null),x=v&&typeof v.validations==="object"&&v.validations!==null?v.validations:null;j.responses=Xt(v,j.responses);let m=v?.requestHeaders;if(m&&typeof m==="object")for(let[a,l]of Object.entries(m)){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(_);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(),ve)),{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 M{static instance=new M;isMissing(){return!0}}class ie{data;constructor(e){this.data=e}}class gt{condition;value;defaultValue;constructor(e,t,n=new M){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class mt{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:M.instance}whenNotNull(e,t){if(e===null||e===void 0)return M.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:M.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 Number(n[r]);return t!==void 0?t:M.instance}merge(e){return new ie(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return M.instance;let r=typeof t==="function"?t():t;return new ie(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=mt.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof M)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 M))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 M)).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 ht 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 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 Rn(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function kn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{gt as ConditionalValue,mt as JsonResource,ie as MergeValue,M as MissingValue,ht as PaginatedResourceCollection,je as ResourceCollection,kn as collection,Xt as describedResponses,en as fetcher,wn as generateOpenApi,qe as methodName,Vt as modelDefinitionToSchema,Dt as renderApiClient,Tt as renderOpenApiTypes,Rn as resource,zt as ruleIsRequired,ft as ruleToSchema,F as schemaType};
|
|
139
|
+
`}var qt;var me=Y(()=>{le();qt=["get","put","post","delete","options","head","patch"]});function Bt(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 we(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(Bt(e))return{status:409,body:{error:`${t} already exists`}};return{status:500,body:{error:`Failed to ${n} ${t}`,detail:String(e)}}}function j(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function be(e){let t={};for(let[n,r]of Object.entries(e))t[j(n)]=r;return t}function Ue(e,t){let n=String(t||"").replace(/^\/+|\/+$/g,""),r=String(e).replace(/^\/+/,"");return`/api/${n?`${n}/`:""}${r}`}function Je(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 He(e,t,n){let r=Object.keys(e).find((o)=>j(o)===j(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(j(o)===j(t))delete s[o];return s[t]=n,{data:s}}function Le(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=j(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 Re(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=j(r);if(s!==r&&s in e)n[r]=e[s]}return n}function Mt(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 ke(e,t){if(!t.length)return e;let n={...e};for(let r of t)delete n[r],delete n[j(r)];return n}function ee(e,t){if(!e||t.length===0)return e;let n={...e};for(let r of t)delete n[r],delete n[j(r)];return n}function Qe(e,t){let n=new Map;for(let r of[...Object.keys(e??{}),...Ft]){let s=j(r);if(!/^\w+$/.test(s))continue;n.set(r,s),n.set(s,s)}for(let r of t)n.delete(r),n.delete(j(r));return n}function We(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 Jt(e){try{return JSON.parse(e)}catch{return e}}function Ht(e){try{return JSON.parse(e)}catch{return[]}}function Se(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"?Ut[o]:o;if(!i||typeof i[n]!=="function")continue;if(Object.prototype.hasOwnProperty.call(r,s))r[s]=i[n](r[s]);let c=j(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=Mt(c,u),w=c.validate(f);if(!w?.valid&&Array.isArray(w?.errors)&&w.errors.length>0)s[o]=w.errors.map((D)=>i?.validation?.message?.[D?.code]??D?.message??"invalid")}return Object.keys(s).length===0?{valid:!0}:{valid:!1,errors:s}}function ze(e,t,n){let r=Me(n);return e.find((s)=>s.method===t&&Me(String(s.path??""))===r)}function Me(e){return e.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function ye(e){if(Array.isArray(e))return e.filter((t)=>typeof t==="string"&&t.length>0);return typeof e==="string"&&e?[e]:[]}function Ve(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?ye(s.read):["auth"],write:"write"in s?ye(s.write):["auth"],declared:!0}}let r=ye(n);return{read:r,write:r,declared:!0}}function Ge(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(Fe),10),s=Math.min(Number.isFinite(r)?Math.max(1,r):Fe,Lt);return{page:n,perPage:s,offset:(n-1)*s}}function pe(e,t){let n=new URL(e.toString());return n.searchParams.set("page",String(t)),`${n.pathname}${n.search}`}function fe(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?pe(e,t-1):null,next_page_url:s?pe(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=pe(e,1),p.last_page_url=pe(e,d)}return p}function $e(e,t,n,r,s,o){let{page:i,...c}=fe(e,t,n,r,s,o);return{current_page:i,...c}}function Ae(e,t){return(t??e??"").toString().trim().toLowerCase()==="deny"?"deny":"warn"}function Xe(e,t){if(e.length===0)return null;let n=[...e].sort().join(", ");if(t==="deny")return`[orm] security.api.rowScoping is 'deny': NOT registering store/update/destroy for ${e.length} model(s) `+`with no row-level scoping \u2014 ${n}. Give a model an \`ownership\` config or a \`team_id\` column to restore its writes.`;return`[orm] ${e.length} model(s) publish mutating routes with no row-level scoping, so an authenticated caller can write any row \u2014 `+`${n}. Scope one with an \`ownership\` config or a \`team_id\` column; intended for public catalog tables. Set \`security.api.rowScoping: 'deny'\` (config/security.ts) to stop generating these routes instead.`}var Ft,Ut,Fe=15,Lt=100;var Ke=Y(()=>{Ft=["id","uuid","created_at","updated_at","deleted_at"];Ut={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"?Jt(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"?Ht(e):[],set:(e)=>e==null?null:Array.isArray(e)?JSON.stringify(e):e}}});var tt={};de(tt,{loadModelRegistry:()=>Te,modelFiles:()=>et});import{readdirSync as Qt}from"fs";import{basename as Wt,extname as Ye,join as zt}from"path";function et(e){let t=[],n=(r)=>{let s;try{s=Qt(r,{withFileTypes:!0})}catch{return}for(let o of s){let i=zt(r,o.name);if(o.isDirectory()){n(i);continue}if(![".ts",".js"].includes(Ye(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 et(e))try{let s=Ye(r),o=await import(`${r}?t=${Date.now()}`),i=o.default??o,c=i.name??Wt(r,s);t[c]={...i,name:c}}catch(s){n?.(r,s)}}async function Te(e){let t={};return await Ze(e.defaultsRoot,t,e.onImportError),await Ze(e.userRoot,t,e.onImportError),t}var _e=()=>{};import Vt from"process";import{route as W}from"@stacksjs/router";import{env as X}from"@stacksjs/env";import{projectPath as je,storagePath as Gt}from"@stacksjs/path";import{createQueryBuilder as Xt,defaultConfig as nt,setConfig as rt}from"@stacksjs/query-builder";import{HttpError as V}from"@stacksjs/error-handling";import{log as re}from"@stacksjs/logging";function K(e,t){let n=ze(W.routes,e,t);if(!n)return!1;let r=String(n.path??"");return re.info(`[orm] Skipping generated ${e} ${t} - already defined${r&&r!==t?` as ${r}`:""}.`),!0}function ut(e){if(!e.attributes)return[];return Object.entries(e.attributes).filter(([t,n])=>n.hidden===!0).map(([t])=>t)}function st(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 ot(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(j(d),{kind:"belongsTo",modelName:d});for(let d of c)p.set(j(d),{kind:"hasOne",modelName:d});for(let d of i)p.set(st(j(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 w=f.table||st(j(u.modelName)),D=ut(f),k=(q)=>ee(ae(q,f),D);if(u.kind==="belongsTo"||u.kind==="hasOne"){let q=`${j(u.modelName)}_id`,_=[...new Set(e.map((A)=>A[q]).filter((A)=>A!=null))];if(!_.length){for(let A of e)A[d]=null;continue}let M=await I.selectFrom(w).whereIn("id",_).get(),E=new Map;for(let A of M??[])E.set(String(A.id),k(A));for(let A of e)A[d]=E.get(String(A[q]))??null}else{let q=String(t.name??""),_=`${j(q)}_id`,M=[...new Set(e.map((x)=>x.id).filter((x)=>x!=null))];if(!M.length){for(let x of e)x[d]=[];continue}let E=await I.selectFrom(w).whereIn(_,M).get(),A=new Map;for(let x of E??[]){let O=String(x[_]),g=A.get(O)??[];g.push(k(x)),A.set(O,g)}for(let x of e)x[d]=A.get(String(x.id))??[]}}return e}async function it(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 at(e,t){return Se(e,t?.casts,"set")}function ae(e,t){return Se(e,t?.casts,"get")}function m(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}async function Pe(e){if(Number(e.headers?.get?.("content-length")??0)>ge)throw new V(413,`Request body exceeds ${ge}-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>ge)throw new V(413,`Request body exceeds ${ge}-byte limit`);if(!n)return{};let r=JSON.parse(n);return r&&typeof r==="object"&&!Array.isArray(r)?r:{}}catch(n){if(n instanceof V)throw n;throw new V(400,`Invalid JSON body: ${n.message}`)}}function he(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 dt(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 te(e){let t=e._authenticatedUser;if(t)return t;let n=dt(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 ie(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 Yt(e){let t=dt(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 lt(e){if(e?.ownership)return e.ownership;let t=Je(e);if(!t)return null;return{field:t,resolve:async(n,r)=>{let{resolveAuthenticatedTeamId:s}=await import("@stacksjs/auth");return s(Yt(r))}}}async function ne(e,t,n){let r=lt(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 ct(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 Kt,xe,Zt,I,ge=1048576,pt,ft,gt;var ht=Y(async()=>{Ke();_e();Kt=je("config/qb.ts");try{let e=(await import(Kt)).default;rt(e??nt)}catch{re.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let e=X.DB_CONNECTION||"sqlite";rt({...nt,dialect:e,database:e==="sqlite"?{database:X.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:X.DB_DATABASE||"stacks",host:X.DB_HOST||"127.0.0.1",port:X.DB_PORT||(e==="postgres"?5432:3306),username:X.DB_USERNAME||(e==="postgres"?"postgres":"root"),password:X.DB_PASSWORD||""}})}xe=await Te({defaultsRoot:Gt("framework/defaults/app/Models"),userRoot:je("app/Models"),onImportError:(e,t)=>re.warn(`[orm] Could not load model ${e}: ${t.message}`)}),Zt=Xt(),I=Zt;pt=await(async()=>{let e=Vt.env.STACKS_API_ROW_SCOPING;try{let t=(await import(je("config/security.ts"))).default;return Ae(t?.api?.rowScoping,e)}catch{return Ae(void 0,e)}})(),ft=[];for(let[e,t]of Object.entries(xe)){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=Le(t),p=ut(t),d=Ue(s,r.prefix),u=Qe(t.attributes,p),{read:f,write:w,declared:D}=Ve(n),k=["store","update","destroy"].some((g)=>o.includes(g));if(k&&D&&w.length===0)re.warn(`[orm] ${e}: registering UNAUTHENTICATED mutating routes at ${d} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((g)=>o.includes(g))&&D&&f.length===0)re.debug(`[orm] ${e}: registering public read routes at ${d} (declared \`middleware.read: []\`)`);let _=!!lt(t),M=_&&!f.includes("auth")?["auth",...f]:f,E=k&&!_;if(E)ft.push(e);let A=E&&pt==="deny",x=(g,a=M)=>{let l=g;for(let h of a)if(l&&typeof l.middleware==="function")l=l.middleware(h);return l};if(o.includes("index")&&!K("GET",d))x(W.get(d,async(g)=>{try{let a=new URL(g.url),{page:l,perPage:h,offset:S}=Ge(a.searchParams),R=a.searchParams.get("sort"),y=I.selectFrom(i);y=We(y,R,u);let F=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[N,C]of a.searchParams.entries()){if(F.has(N)||!C)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(N))continue;let G=u.get(N);if(G)y=y.where(G,"=",C)}let P=a.searchParams.get("search");if(P&&c.length>0){let N=c.slice(0,5);y=y.where((C)=>{for(let G of N)C=C.orWhere(j(G),"like",`%${P}%`);return C})}let v=a.searchParams.get("fields");if(v){let N=v.split(",").map((C)=>C.trim()).filter((C)=>/^[a-z_][a-z0-9_]*$/i.test(C)).map((C)=>j(C));if(N.length>0)y=y.select(N)}let B=!!t.traits?.useSoftDeletes,T=a.searchParams.get("withTrashed")==="true",H=a.searchParams.get("onlyTrashed")==="true";if(B&&!T)y=H?y.whereNotNull("deleted_at"):y.whereNull("deleted_at");let b=_?await ne(t,await te(g),g):{enforced:!1,value:null,field:"",bypass:!1};if(b.enforced&&!b.bypass){if(b.value==null||Array.isArray(b.value)&&b.value.length===0){let N=$e(a,l,h,0,!1,void 0);return new Response(JSON.stringify({data:[],...N,meta:fe(a,l,h,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}y=Array.isArray(b.value)?y.where(b.field,"in",b.value):y.where(b.field,"=",b.value)}let L=await y.limit(h+1).offset(S).get()||[],Q=L.length>h,oe=(Q?L.slice(0,h):L).map((N)=>ee(ae(N,t),p)),ve=a.searchParams.get("include");if(ve)oe=await ot(oe,t,ve,xe);let Ot=a.searchParams.get("with_count")==="true",Z;if(Ot)try{let N=I.selectFrom(i);if(b.enforced&&!b.bypass&&b.value!=null)N=Array.isArray(b.value)?N.where(b.field,"in",b.value):N.where(b.field,"=",b.value);let C=await N.count(),G=typeof C==="number"?C:Number(C?.count??C);if(Number.isFinite(G))Z=G}catch{}let ue={"Content-Type":"application/json"};if(Z!==void 0&&!Number.isNaN(Z))ue["X-Total-Count"]=String(Z);ue["Cache-Control"]=b.enforced&&!b.bypass?"private, no-store":"public, max-age=15, must-revalidate",ue.Vary="Authorization";let $t=$e(a,l,h,oe.length,Q,Z);return new Response(JSON.stringify({data:oe,...$t,meta:fe(a,l,h,oe.length,Q,Z)}),{status:200,headers:ue})}catch(a){if(a instanceof V){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")&&!K("GET",`${d}/{id}`))x(W.get(`${d}/{id}`,async(g)=>{try{let a=he(g.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await I.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let h=new URL(g.url);if(t.traits?.useSoftDeletes&&l.deleted_at&&h.searchParams.get("withTrashed")!=="true")return m({error:`${e} not found`},404);let S=_?await ne(t,await te(g),g):{enforced:!1,value:null,field:"",bypass:!1};if(S.enforced&&!S.bypass){if(S.value==null||!ie(l[S.field],S.value))return m({error:`${e} not found`},404)}let R=ee(ae(l,t),p),y=h.searchParams.get("include");if(y){let[T]=await ot([R],t,y,xe);R=T}let F=R?.updated_at||R?.created_at,P=F?`W/"${R.id}-${String(F)}"`:void 0,v=g.headers?.get?.("if-none-match");if(P&&v&&v===P)return new Response(null,{status:304,headers:{ETag:P}});let B={"Content-Type":"application/json"};if(P)B.ETag=P;return B["Cache-Control"]=S.enforced&&!S.bypass?"private, no-store":"public, max-age=30, must-revalidate",B.Vary="Authorization",new Response(JSON.stringify({data:R}),{status:200,headers:B})}catch(a){if(a instanceof V){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(!A&&o.includes("store")&&!K("POST",d))x(W.post(d,async(g)=>{try{let a=await Pe(g),l=ke(a,p),h=Re(l,c),S=await te(g);if(S){let T=await ct(t,"creating",S,g);for(let[H,b]of Object.entries(T))if(b!==void 0&&b!==null&&h[H]===void 0)h[H]=b}let R=await ne(t,S,g);if(R.enforced&&!R.bypass){if(!S)return m({error:"Auth required"},401);let T=He(h,R.field,R.value);if(T.error)return m({error:T.error},403);h=T.data}if(Object.keys(h).length===0)return m({error:"No fillable fields provided"},422);let y=Oe(h,t,"creating");if(!y.valid)return m({success:!1,message:"Validation failed",errors:y.errors},422);if(t.traits?.useTimestamps!==!1){let T=new Date().toISOString();h.created_at=T,h.updated_at=T}let F=await it(h,t),P=be(at(F,t)),v=await I.insertInto(i).values(P).execute(),B=P;try{let T=v?.lastInsertRowid??v?.insertId??v;if(T){let H=await I.selectFrom(i).where({id:T}).executeTakeFirst();if(H)B=H}}catch{}return m({data:ee(ae(B,t),p)},201)}catch(a){let{status:l,body:h}=we(a,e,"create");return m(h,l)}}),w);if(!A&&o.includes("update")){let g=async(a)=>{try{let l=he(a.params?.id);if(l==null)return m({error:"Invalid ID parameter"},400);let h=await Pe(a),S=ke(h,p),R=Re(S,c),y=await te(a);if(y){let b=await ct(t,"updating",y,a);for(let[L,Q]of Object.entries(b))if(Q!==void 0&&Q!==null&&R[L]===void 0)R[L]=Q}if(Object.keys(R).length===0)return m({error:"No fillable fields provided"},422);let F=Oe(R,t,"updating");if(!F.valid)return m({success:!1,message:"Validation failed",errors:F.errors},422);let P=await I.selectFrom(i).where({id:l}).executeTakeFirst();if(!P)return m({error:`${e} not found`},404);let v=await ne(t,y,a);if(v.enforced&&!v.bypass){if(!y)return m({error:"Auth required"},401);let b=P[v.field];if(!ie(b,v.value))return m({error:`Not your ${e}`},403);let L=Object.keys(R).find((Q)=>j(Q)===j(v.field));if(L!==void 0&&!ie(R[L],v.value))return m({error:`Cannot reassign ${e} ownership`},403)}if(t.traits?.useTimestamps!==!1)R.updated_at=new Date().toISOString();let B=await it(R,t),T=be(at(B,t));await I.updateTable(i).set(T).where({id:l}).execute();let H={...P,...T};try{let b=await I.selectFrom(i).where({id:l}).executeTakeFirst();if(b)H=b}catch{}return m({data:ee(ae(H,t),p)})}catch(l){let{status:h,body:S}=we(l,e,"update");return m(S,h)}};if(!K("PUT",`${d}/{id}`))x(W.put(`${d}/{id}`,g),w);if(!K("PATCH",`${d}/{id}`))x(W.patch(`${d}/{id}`,g),w)}let O=!!t.traits?.useSoftDeletes;if(!A&&o.includes("destroy")&&!K("DELETE",`${d}/{id}`))x(W.delete(`${d}/{id}`,async(g)=>{try{let a=he(g.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await I.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let h=await te(g),S=await ne(t,h,g);if(S.enforced&&!S.bypass){if(!h)return m({error:"Auth required"},401);let R=l[S.field];if(!ie(R,S.value))return m({error:`Not your ${e}`},403)}if(O){let R=new Date().toISOString();await I.updateTable(i).set({deleted_at:R,updated_at:R}).where({id:a}).execute()}else await I.deleteFrom(i).where({id:a}).execute();return new Response(null,{status:204})}catch(a){if(a instanceof V){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)}}),w);if(!A&&o.includes("destroy")&&!K("POST",`${d}/bulk-delete`))x(W.post(`${d}/bulk-delete`,async(g)=>{try{let l=(await Pe(g))?.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 h=[],S=[];for(let P of l){let v=he(P);if(v!=null)h.push(v);else S.push(P)}if(S.length>0)return m({error:"Invalid IDs in batch",invalid:S},422);let R=await te(g),y=await ne(t,R,g);if(y.enforced&&!y.bypass){if(!R)return m({error:"Auth required"},401);if(y.value==null)return m({error:"Caller has no ownership identity"},403);let P=await I.selectFrom(i).select(["id",y.field]).execute(),v=new Set(P.filter((T)=>ie(T[y.field],y.value)).map((T)=>String(T.id))),B=h.filter((T)=>!v.has(String(T)));if(B.length>0)return m({error:`Cannot delete ${e} you don't own`,ids:B},403)}let F=new Date().toISOString();for(let P of h)if(O)await I.updateTable(i).set({deleted_at:F,updated_at:F}).where({id:P}).execute();else await I.deleteFrom(i).where({id:P}).execute();return m({message:`Successfully deleted ${h.length} ${s}`})}catch(a){if(a instanceof V){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)}}),w)}{let e=Xe(ft,pt);if(e)re.warn(e)}gt=W});var mt={};de(mt,{default:()=>gt});var yt=Y(async()=>{await ht()});class qe{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 Ne{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((D,k)=>{let[q,_]=k.trim().split("=");if(q)D[q]=_?.replace(/["']/g,"")??"";return D},{}),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((D)=>D.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},w=Object.entries(f).filter(([D,k])=>k!==void 0).map(([D,k])=>`${D}=${k}`).join(", ");return this.customHeaders.Authorization=`Digest ${w}`,fetch(t,{method:n,headers:this.getHeaders(),body:r?await 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 qe(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 cn=new Ne;me();import{path as se}from"@stacksjs/path";function bt(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 w=r(u)?.params?.[f];return typeof w==="number"?w: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 en(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function wt(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function tn(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=wt(r);if(t[o]=bt(s.validation?.rule),s.required===!0)n.push(o)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let s=`${wt(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 nn(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 rn(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 sn(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 Tn(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router");try{let{loadRoutes:u}=await import("@stacksjs/router"),{default:f}=await import(se.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 yt().then(() => mt)}}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(),tt))}r=await f.loadModelRegistry({defaultsRoot:se.storagePath("framework/defaults/app/Models"),userRoot:se.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:nn(u),schema:tn(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:w}of o){if(!c.paths[f])c.paths[f]={};let D=[];for(let O of u.path.matchAll(/\{(\w+)\}/g))if(O[1])D.push(O[1]);for(let O of u.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(O[1])D.push(O[1]);let k=u.name??`${w}_${f.replace(/[^a-z0-9]/gi,"_")}`,q=k;if(d.has(q)){q=`${k}_${w}`;let O=2;while(d.has(q))q=`${k}_${w}_${O++}`}d.add(q);let _={summary:u.name??u.path,operationId:q,parameters:D.map((O)=>({name:O,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"}}},M=p.find((O)=>f===O.path||f===`${O.path}/{id}`);if(M){let O=f===M.path&&w==="get"?{type:"array",items:M.schema}:M.schema;if(_.responses[200].content={"application/json":{schema:{type:"object",properties:{data:O},required:["data"]}}},w==="post"&&f===M.path)_.responses[201]={..._.responses[200],description:"Created"},delete _.responses[200]}let E=u.action??(u.handler?await sn(u.handler):null),A=E&&typeof E.validations==="object"&&E.validations!==null?E.validations:null;_.responses=rn(E,_.responses);let x=E?.requestHeaders;if(x&&typeof x==="object")for(let[O,g]of Object.entries(x)){let a=g;if(!a||typeof a!=="object"||typeof a.description!=="string")continue;_.parameters?.push({name:O,in:"header",description:a.description,required:a.required===!0,schema:a.schema&&typeof a.schema==="object"?a.schema:{type:"string"}})}if(A&&Object.keys(A).length>0){let O=Object.entries(A).map(([g,a])=>{let l=a?.rule;return{field:g,schema:bt(l),required:en(l)}});if(w==="get"||w==="head"||w==="delete"){let g=new Set(D);for(let{field:a,schema:l,required:h}of O){if(g.has(a))continue;_.parameters?.push({name:a,in:"query",required:h,schema:l})}}else{let g={type:"object",properties:{},required:[]},a=g.properties,l=g.required;for(let h of O)if(a[h.field]=h.schema,h.required)l.push(h.field);if(l.length===0)delete g.required;_.requestBody={required:l.length>0,content:{"application/json":{schema:g}}}}}c.paths[f][w]=_}if(e.write!==!1){await Bun.write(se.frameworkPath("api/openapi.json"),JSON.stringify(c,null,2));let{renderOpenApiTypes:u}=await Promise.resolve().then(() => (le(),Ie)),{renderApiClient:f}=await Promise.resolve().then(() => (me(),Be));await Bun.write(se.frameworkPath("api/api-types.ts"),u(c)),await Bun.write(se.frameworkPath("api/client.ts"),f(c,{name:c.info.title}))}return c}le();class J{static instance=new J;isMissing(){return!0}}class ce{data;constructor(e){this.data=e}}class Rt{condition;value;defaultValue;constructor(e,t,n=new J){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class kt{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 De(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:J.instance}whenNotNull(e,t){if(e===null||e===void 0)return J.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:J.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 Number(n[r]);return t!==void 0?t:J.instance}merge(e){return new ce(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return J.instance;let r=typeof t==="function"?t():t;return new ce(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=kt.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof J)continue;if(s instanceof ce){Object.assign(n,this.filterAndResolve(s.data,t+1));continue}if(s instanceof Rt){let o=s.resolve();if(!(o instanceof J))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 J)).map((o)=>{if(o instanceof ce)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 De{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 St extends De{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 St({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 xn(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function Pn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{Rt as ConditionalValue,kt as JsonResource,ce as MergeValue,J as MissingValue,St as PaginatedResourceCollection,De as ResourceCollection,Pn as collection,rn as describedResponses,cn as fetcher,Tn as generateOpenApi,Ee as methodName,tn as modelDefinitionToSchema,Et as renderApiClient,vt as renderOpenApiTypes,xn as resource,en as ruleIsRequired,bt as ruleToSchema,U 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.
|
|
5
|
+
"version": "0.74.0",
|
|
6
6
|
"description": "The Stacks API utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -60,8 +60,13 @@
|
|
|
60
60
|
"typecheck": "bun tsc --noEmit",
|
|
61
61
|
"prepublishOnly": "bun run build"
|
|
62
62
|
},
|
|
63
|
+
"dependencies": {
|
|
64
|
+
"@stacksjs/config": "0.74.0",
|
|
65
|
+
"@stacksjs/path": "0.74.0",
|
|
66
|
+
"@stacksjs/router": "0.74.0"
|
|
67
|
+
},
|
|
63
68
|
"devDependencies": {
|
|
64
|
-
"
|
|
65
|
-
"
|
|
69
|
+
"@stacksjs/utils": "0.74.0",
|
|
70
|
+
"better-dx": "^0.2.24"
|
|
66
71
|
}
|
|
67
72
|
}
|