@stacksjs/api 0.74.53 → 0.74.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +11 -11
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  // @bun
2
- var X=Object.defineProperty;var K=(e)=>e;function Y(e,t){this[e]=K.bind(null,t)}var ee=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Y.bind(t,n)})};var P=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function ne(e){return typeof e==="string"?JSON.stringify(e):String(e)}function O(e){if(!e)return"unknown";if(e.enum?.length)return e.enum.map(ne).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<${O(e.items)}>`;if(e.type==="object"||e.properties||e.additionalProperties){let t=new Set(e.required||[]),n=Object.entries(e.properties||{}).map(([r,o])=>`${JSON.stringify(r)}${t.has(r)?"":"?"}: ${O(o)}`);if(e.additionalProperties){let r=e.additionalProperties===!0?"unknown":O(e.additionalProperties);n.push(`[key: string]: ${r}`)}return n.length?`{ ${n.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function re(e=[]){return` parameters: {
3
- ${["query","header","path","cookie"].map((n)=>{let r=e.filter((s)=>s.in===n);if(!r.length)return` ${n}?: never`;let o=r.map((s)=>`${JSON.stringify(s.name)}${s.required?"":"?"}: ${O(s.schema)}`);return` ${n}${r.every((s)=>!s.required)?"?":""}: { ${o.join("; ")} }`}).join(`
2
+ var Y=Object.defineProperty;var ee=(e)=>e;function te(e,t){this[e]=ee.bind(null,t)}var ne=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0,configurable:!0,set:te.bind(t,n)})};var x=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function se(e){return typeof e==="string"?JSON.stringify(e):String(e)}function w(e){if(!e)return"unknown";if(e.enum?.length)return e.enum.map(se).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<${w(e.items)}>`;if(e.type==="object"||e.properties||e.additionalProperties){let t=new Set(e.required||[]),n=Object.entries(e.properties||{}).map(([r,o])=>`${JSON.stringify(r)}${t.has(r)?"":"?"}: ${w(o)}`);if(e.additionalProperties){let r=e.additionalProperties===!0?"unknown":w(e.additionalProperties);n.push(`[key: string]: ${r}`)}return n.length?`{ ${n.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function oe(e=[]){return` parameters: {
3
+ ${["query","header","path","cookie"].map((n)=>{let r=e.filter((s)=>s.in===n);if(!r.length)return` ${n}?: never`;let o=r.map((s)=>`${JSON.stringify(s.name)}${s.required?"":"?"}: ${w(s.schema)}`);return` ${n}${r.every((s)=>!s.required)?"?":""}: { ${o.join("; ")} }`}).join(`
4
4
  `)}
5
- }`}function F(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${O(n.schema)}`).join("; ")} }`}function se(e){let t=e.requestBody?`
5
+ }`}function F(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${w(n.schema)}`).join("; ")} }`}function ie(e){let t=e.requestBody?`
6
6
  requestBody${e.requestBody.required?"":"?"}: { content: ${F(e.requestBody.content)} }`:`
7
7
  requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,o])=>` ${JSON.stringify(r)}: { content: ${F(o.content)} }`);return`{
8
- ${re(e.parameters)}${t}
8
+ ${oe(e.parameters)}${t}
9
9
  responses: {
10
10
  ${n.join(`
11
11
  `)}
12
12
  }
13
- }`}function M(e){let t=Object.entries(e.paths||{}).map(([r,o])=>{let s=te.map((a)=>{let c=o[a];return c?` ${a}: ${se(c)}`:` ${a}?: never`});return` ${JSON.stringify(r)}: {
13
+ }`}function M(e){let t=Object.entries(e.paths||{}).map(([r,o])=>{let s=re.map((a)=>{let c=o[a];return c?` ${a}: ${ie(c)}`:` ${a}?: never`});return` ${JSON.stringify(r)}: {
14
14
  ${s.join(`
15
15
  `)}
16
- }`}),n=Object.entries(e.components?.schemas||{}).map(([r,o])=>` ${JSON.stringify(r)}: ${O(o)}`);return`/**
16
+ }`}),n=Object.entries(e.components?.schemas||{}).map(([r,o])=>` ${JSON.stringify(r)}: ${w(o)}`);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 te;var v=P(()=>{te=["get","put","post","delete","options","head","patch","trace"]});function ie(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,...o]=n;if(!r)return"call";let s=r.charAt(0).toLowerCase()+r.slice(1),a=o.map((p)=>p.charAt(0).toUpperCase()+p.slice(1)),c=[s,...a].join("");return/^[a-z_$]/i.test(c)?c:`call${c.charAt(0).toUpperCase()}${c.slice(1)}`}function ae(e){let t=e.responses??{},n=Object.keys(t).find((s)=>s.startsWith("2"));if(!n)return"unknown";let r=t[n]?.content,o=r?.["application/json"]??Object.values(r??{})[0];return o?.schema?O(o.schema):"unknown"}function ce(e,t=" "){let n=e.filter(Boolean);if(!n.length)return"";return`${t}/**
32
+ `}var re;var D=x(()=>{re=["get","put","post","delete","options","head","patch","trace"]});function ce(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,...o]=n;if(!r)return"call";let s=r.charAt(0).toLowerCase()+r.slice(1),a=o.map((d)=>d.charAt(0).toUpperCase()+d.slice(1)),c=[s,...a].join("");return/^[a-z_$]/i.test(c)?c:`call${c.charAt(0).toUpperCase()}${c.slice(1)}`}function ue(e){let t=e.responses??{},n=Object.keys(t).find((s)=>s.startsWith("2"));if(!n)return"unknown";let r=t[n]?.content,o=r?.["application/json"]??Object.values(r??{})[0];return o?.schema?w(o.schema):"unknown"}function pe(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 ue(e,t,n,r){let o=n.parameters??[],s=o.filter((d)=>d.in==="path"),a=o.filter((d)=>d.in==="query"),c=n.requestBody?.content?.["application/json"]?.schema,p=Boolean(n.requestBody?.required),l=[];for(let d of[...s,...a]){let b=d.in==="path"||d.required;l.push(`${JSON.stringify(d.name)}${b?"":"?"}: ${O(d.schema)}`)}if(c)l.push(`body${p?"":"?"}: ${O(c)}`);let i=[...s,...a].every((d)=>d.in!=="path"&&!d.required)&&(!c||!p),u=l.length?`input${i?"?":""}: { ${l.join("; ")} }, `:"",f=a.length?`[${a.map((d)=>JSON.stringify(d.name)).join(", ")}]`:"[]";return`${ce([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${u}options?: RequestOptions): Promise<ApiResult<${ae(n)}>> {
37
- return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${l.length?"input ?? {}":"{}"}, ${f}, ${c?"true":"false"}, options)
38
- },`}function H(e,t={}){let n=t.name??"API",r=new Map,o=[];for(let[s,a]of Object.entries(e.paths??{}))for(let c of oe){let p=a[c];if(!p)continue;let l=ie(p.operationId??`${c}_${s}`),i=r.get(l)??0;r.set(l,i+1),o.push(ue(s,c,p,i===0?l:`${l}${i+1}`))}return`/* eslint-disable */
36
+ `}function de(e,t,n,r){let o=n.parameters??[],s=o.filter((p)=>p.in==="path"),a=o.filter((p)=>p.in==="query"),c=n.requestBody?.content?.["application/json"]?.schema,d=Boolean(n.requestBody?.required),l=[];for(let p of[...s,...a]){let O=p.in==="path"||p.required;l.push(`${JSON.stringify(p.name)}${O?"":"?"}: ${w(p.schema)}`)}if(c)l.push(`body${d?"":"?"}: ${w(c)}`);let m=[...s,...a].every((p)=>p.in!=="path"&&!p.required)&&(!c||!d),g=l.length?`input${m?"?":""}: { ${l.join("; ")} }, `:"",i=a.length?`[${a.map((p)=>JSON.stringify(p.name)).join(", ")}]`:"[]";return`${pe([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${g}options?: RequestOptions): Promise<ApiResult<${ue(n)}>> {
37
+ return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${l.length?"input ?? {}":"{}"}, ${i}, ${c?"true":"false"}, options)
38
+ },`}function H(e,t={}){let n=t.name??"API",r=new Map,o=[];for(let[s,a]of Object.entries(e.paths??{}))for(let c of ae){let d=a[c];if(!d)continue;let l=ce(d.operationId??`${c}_${s}`),m=r.get(l)??0;r.set(l,m+1),o.push(de(s,c,d,m===0?l:`${l}${m+1}`))}return`/* eslint-disable */
39
39
  /**
40
40
  * ${n} client, generated from the OpenAPI document.
41
41
  *
@@ -136,4 +136,4 @@ ${o.join(`
136
136
  }
137
137
 
138
138
  export type Client = ReturnType<typeof createClient>
139
- `}var oe;var B=P(()=>{v();oe=["get","put","post","delete","options","head","patch"]});var N=()=>{};var U={};ee(U,{loadModelRegistry:()=>he,modelFiles:()=>L});import{readdirSync as pe}from"fs";import{basename as de,extname as I,join as le}from"path";function L(e){let t=[],n=(r)=>{let o;try{o=pe(r,{withFileTypes:!0})}catch{return}for(let s of o){let a=le(r,s.name);if(s.isDirectory()){n(a);continue}if(![".ts",".js"].includes(I(s.name)))continue;if(s.name.startsWith(".")||s.name.startsWith("index"))continue;t.push(a)}};return n(e),t.sort()}async function E(e,t,n){for(let r of L(e))try{let o=I(r),s=await import(`${r}?t=${Date.now()}`),a=s.default??s,c=a.name??de(r,o);t[c]={...a,name:c}}catch(o){n?.(r,o)}}async function he(e){let t={};return await E(e.defaultsRoot,t,e.onImportError),await E(e.userRoot,t,e.onImportError),t}var V=()=>{};class _{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 J{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 o=typeof t==="string"?new Blob([t],{type:r?.["Content-Type"]||"text/plain"}):t;return this.attachments.push({name:e,content:o,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(([o,s])=>{if(s!=null)t.append(o,String(s))});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,o])=>{n.append(r,String(o))});for(let r of this.attachments)if(r.headers){let o=r.content instanceof Blob?new Blob([r.content],{type:r.headers["Content-Type"]}):r.content;n.append(r.name,o,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,o])=>{if(o!=null)n.append(r,String(o))}),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 o=e.headers.get("WWW-Authenticate");if(!o?.startsWith("Digest "))return e;let s=o.substring(7).split(",").reduce((g,d)=>{let[b,y]=d.trim().split("=");if(b)g[b]=y?.replace(/["']/g,"")??"";return g},{}),a=await this.generateMD5(`${this.digestAuth.username}:${s.realm}:${this.digestAuth.password}`),c=await this.generateMD5(`${n}:${t}`),p="00000001",l=await this.generateMD5(Date.now().toString()).then((g)=>g.substring(0,8)),i=await this.generateMD5(`${a}:${s.nonce}:${p}:${l}:${s.qop}:${c}`),u={username:`"${this.digestAuth.username}"`,realm:`"${s.realm}"`,nonce:`"${s.nonce}"`,uri:`"${t}"`,algorithm:s.algorithm?`"${s.algorithm}"`:void 0,qop:`"${s.qop}"`,nc:p,cnonce:`"${l}"`,response:`"${i}"`,opaque:s.opaque?`"${s.opaque}"`:void 0},f=Object.entries(u).filter(([g,d])=>d!==void 0).map(([g,d])=>`${g}=${d}`).join(", ");return this.customHeaders.Authorization=`Digest ${f}`,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((s)=>s.toString(16).padStart(2,"0")).join("")}async request(e,t,n){let r=this.addQueryParams(e),o=await this.formatBody(n),s=await fetch(r,{method:t,headers:this.getHeaders(),body:o});if(this.digestAuth)s=await this.handleDigestAuth(s,r,t,n);let a=await s.json();return this.resetState(),new _(a,s.status,s.headers,s.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 we=new J;B();import{path as S}from"@stacksjs/path";function z(e){if(!e||typeof e!=="object")return{type:"string"};let t=e,n=Array.isArray(t.rules)?t.rules:[],r=(i)=>n.find((u)=>u.name===i),o=(i,u)=>{let f=r(i)?.params?.[u];return typeof f==="number"?f:void 0},s=t.name??t._type??"string",a={type:s==="enum"?"string":s},c=o("min","min")??(typeof t._min==="number"?t._min:void 0),p=o("max","max")??(typeof t._max==="number"?t._max:void 0);if(c!==void 0)a[s==="string"?"minLength":"minimum"]=c;if(p!==void 0)a[s==="string"?"maxLength":"maximum"]=p;if(r("email")||t._email)a.format="email";if(r("url")||t._url)a.format="uri";if(r("uuid")||t._uuid)a.format="uuid";let l=Array.isArray(t.allowedValues)?t.allowedValues:Array.isArray(t._enum)?t._enum:null;if(l)a.enum=l;return a}function fe(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function W(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function me(e){let t={id:{type:"integer"}},n=["id"];if(e.traits?.useUuid)t.uuid={type:"string",format:"uuid"},n.push("uuid");for(let[r,o]of Object.entries(e.attributes??{})){if(o.hidden===!0)continue;let s=W(r);if(t[s]=z(o.validation?.rule),o.required===!0)n.push(s)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let o=`${W(r.trim())}_id`;t[o]??={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 ge(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 ye(e,t){let n={...t},r=e?.responses;if(r&&typeof r==="object")for(let[s,a]of Object.entries(r)){let c=a;if(!c||typeof c!=="object"||typeof c.description!=="string")continue;n[String(s)]={description:c.description,...c.schema&&typeof c.schema==="object"?{content:{"application/json":{schema:c.schema}}}:{}}}let o=e?.responseHeaders;if(o&&typeof o==="object"){let s={};for(let[a,c]of Object.entries(o)){let p=c;if(!p||typeof p!=="object"||typeof p.description!=="string")continue;s[a]={description:p.description,...p.schema&&typeof p.schema==="object"?{schema:p.schema}:{}}}if(Object.keys(s).length>0)for(let a of Object.keys(n))n[a]={...n[a],headers:s}}return n}async function be(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 a=(await import(r)).default;return a&&typeof a==="object"?a:null}catch{}}catch{}return null}async function ve(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router");try{let{loadRoutes:i}=await import("@stacksjs/router"),{default:u}=await import(S.appPath("Routes.ts"));await i(u)}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${u}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${u}`)}try{try{await import("@stacksjs/orm/routes")}catch{await Promise.resolve().then(() => (N(),{}))}}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${u}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${u}`)}let r={};try{let u;try{u=await import("@stacksjs/orm/model-registry")}catch{u=await Promise.resolve().then(() => (V(),U))}r=await u.loadModelRegistry({defaultsRoot:S.storagePath("framework/defaults/app/Models"),userRoot:S.projectPath("app/Models")})}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${u}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${u}`)}let o=(i)=>i.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),s=[...n()].map((i)=>({route:i,oasPath:o(i.path),method:i.method.toLowerCase()})).sort((i,u)=>{if(i.oasPath!==u.oasPath)return i.oasPath<u.oasPath?-1:1;return i.method<u.method?-1:i.method>u.method?1:0});if(t&&s.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 a="Stacks API";if(!t)try{let{config:i}=await import("@stacksjs/config");if(i.app?.name)a=`${i.app.name} API`}catch{}let c={openapi:"3.0.0",info:{title:a,version:"1.0.0"},paths:{},components:{schemas:{}}},p=Object.values(r).map((i)=>({name:String(i.name),path:ge(i),schema:me(i)})).filter((i)=>i.path!==null).sort((i,u)=>i.name<u.name?-1:i.name>u.name?1:0);for(let i of p)c.components.schemas[i.name]=i.schema;let l=new Set;for(let{route:i,oasPath:u,method:f}of s){if(!c.paths[u])c.paths[u]={};let g=[];for(let h of i.path.matchAll(/\{(\w+)\}/g))if(h[1])g.push(h[1]);for(let h of i.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(h[1])g.push(h[1]);let d=i.name??`${f}_${u.replace(/[^a-z0-9]/gi,"_")}`,b=d;if(l.has(b)){b=`${d}_${f}`;let h=2;while(l.has(b))b=`${d}_${f}_${h++}`}l.add(b);let y={summary:i.name??i.path,operationId:b,parameters:g.map((h)=>({name:h,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"}}},k=p.find((h)=>u===h.path||u===`${h.path}/{id}`);if(k){let h=u===k.path&&f==="get"?{type:"array",items:k.schema}:k.schema;if(y.responses[200].content={"application/json":{schema:{type:"object",properties:{data:h},required:["data"]}}},f==="post"&&u===k.path)y.responses[201]={...y.responses[200],description:"Created"},delete y.responses[200]}let j=i.action??(i.handler?await be(i.handler):null),x=j&&typeof j.validations==="object"&&j.validations!==null?j.validations:null;y.responses=ye(j,y.responses);let D=j?.requestHeaders;if(D&&typeof D==="object")for(let[h,w]of Object.entries(D)){let m=w;if(!m||typeof m!=="object"||typeof m.description!=="string")continue;y.parameters?.push({name:h,in:"header",description:m.description,required:m.required===!0,schema:m.schema&&typeof m.schema==="object"?m.schema:{type:"string"}})}if(x&&Object.keys(x).length>0){let h=Object.entries(x).map(([w,m])=>{let A=m?.rule;return{field:w,schema:z(A),required:fe(A)}});if(f==="get"||f==="head"||f==="delete"){let w=new Set(g);for(let{field:m,schema:A,required:q}of h){if(w.has(m))continue;y.parameters?.push({name:m,in:"query",required:q,schema:A})}}else{let w={type:"object",properties:{},required:[]},{properties:m,required:A}=w;for(let q of h)if(m[q.field]=q.schema,q.required)A.push(q.field);if(A.length===0)delete w.required;y.requestBody={required:A.length>0,content:{"application/json":{schema:w}}}}}c.paths[u][f]=y}if(e.write!==!1){await Bun.write(S.frameworkPath("api/openapi.json"),JSON.stringify(c,null,2));await Promise.resolve().then(() => v());await Promise.resolve().then(() => B());await Bun.write(S.frameworkPath("api/api-types.ts"),M(c)),await Bun.write(S.frameworkPath("api/client.ts"),H(c,{name:c.info.title}))}return c}v();class R{static instance=new R;isMissing(){return!0}}class T{data;constructor(e){this.data=e}}class Q{condition;value;defaultValue;constructor(e,t,n=new R){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class G{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 C(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:R.instance}whenNotNull(e,t){if(e===null||e===void 0)return R.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:R.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:R.instance}merge(e){return new T(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return R.instance;let r=typeof t==="function"?t():t;return new T(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=G.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,o]of Object.entries(e)){if(o instanceof R)continue;if(o instanceof T){Object.assign(n,this.filterAndResolve(o.data,t+1));continue}if(o instanceof Q){let s=o.resolve();if(!(s instanceof R))n[r]=s;continue}if(o!==null&&typeof o==="object"&&!Array.isArray(o)&&!(o instanceof Date)){n[r]=this.filterAndResolve(o,t+1);continue}if(Array.isArray(o)){n[r]=o.filter((s)=>!(s instanceof R)).map((s)=>{if(s instanceof T)return s.data;if(s!==null&&typeof s==="object"&&!(s instanceof Date))return this.filterAndResolve(s,t+1);return s});continue}n[r]=o}return n}static withoutWrapping(){this.wrap=null}static wrapWith(e){this.wrap=e}}class C{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 Z extends C{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:o,total:s,baseUrl:a=""}=n,c=Math.ceil(s/o),p=s>0?(r-1)*o+1:null,l=s>0?Math.min(r*o,s):null;return new Z({data:e,meta:{current_page:r,from:p,last_page:c,per_page:o,to:l,total:s},links:{first:`${a}?page=1`,last:`${a}?page=${c}`,prev:r>1?`${a}?page=${r-1}`:null,next:r<c?`${a}?page=${r+1}`:null}},t)}toResponse(e){return{data:this.resolve(e),meta:this.meta,links:this.links,...this.additional}}}function De(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function Be(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{Q as ConditionalValue,G as JsonResource,T as MergeValue,R as MissingValue,Z as PaginatedResourceCollection,C as ResourceCollection,Be as collection,ye as describedResponses,we as fetcher,ve as generateOpenApi,ie as methodName,me as modelDefinitionToSchema,H as renderApiClient,M as renderOpenApiTypes,De as resource,fe as ruleIsRequired,z as ruleToSchema,O as schemaType};
139
+ `}var ae;var _=x(()=>{D();ae=["get","put","post","delete","options","head","patch"]});var I=()=>{};var W={};ne(W,{loadModelRegistry:()=>me,modelFiles:()=>V});import{readdirSync as le}from"fs";import{basename as he,extname as U,join as fe}from"path";function V(e){let t=[],n=(r)=>{let o;try{o=le(r,{withFileTypes:!0})}catch{return}for(let s of o){let a=fe(r,s.name);if(s.isDirectory()){n(a);continue}if(![".ts",".js"].includes(U(s.name)))continue;if(s.name.startsWith(".")||s.name.startsWith("index"))continue;t.push(a)}};return n(e),t.sort()}async function L(e,t,n){for(let r of V(e))try{let o=U(r),s=await import(`${r}?t=${Date.now()}`),a=s.default??s,c=a.name??he(r,o);t[c]={...a,name:c}}catch(o){n?.(r,o)}}async function me(e){let t={};return await L(e.defaultsRoot,t,e.onImportError),await L(e.userRoot,t,e.onImportError),t}var z=()=>{};class N{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 J{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 o=typeof t==="string"?new Blob([t],{type:r?.["Content-Type"]||"text/plain"}):t;return this.attachments.push({name:e,content:o,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(([o,s])=>{if(s!=null)t.append(o,String(s))});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,o])=>{n.append(r,String(o))});for(let r of this.attachments)if(r.headers){let o=r.content instanceof Blob?new Blob([r.content],{type:r.headers["Content-Type"]}):r.content;n.append(r.name,o,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,o])=>{if(o!=null)n.append(r,String(o))}),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 o=e.headers.get("WWW-Authenticate");if(!o?.startsWith("Digest "))return e;let s=o.substring(7).split(",").reduce((u,p)=>{let[O,P]=p.trim().split("=");if(O)u[O]=P?.replace(/["']/g,"")??"";return u},{}),a=await this.generateMD5(`${this.digestAuth.username}:${s.realm}:${this.digestAuth.password}`),c=await this.generateMD5(`${n}:${t}`),d="00000001",l=await this.generateMD5(Date.now().toString()).then((u)=>u.substring(0,8)),m=await this.generateMD5(`${a}:${s.nonce}:${d}:${l}:${s.qop}:${c}`),g={username:`"${this.digestAuth.username}"`,realm:`"${s.realm}"`,nonce:`"${s.nonce}"`,uri:`"${t}"`,algorithm:s.algorithm?`"${s.algorithm}"`:void 0,qop:`"${s.qop}"`,nc:d,cnonce:`"${l}"`,response:`"${m}"`,opaque:s.opaque?`"${s.opaque}"`:void 0},i=Object.entries(g).filter(([u,p])=>p!==void 0).map(([u,p])=>`${u}=${p}`).join(", ");return this.customHeaders.Authorization=`Digest ${i}`,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((s)=>s.toString(16).padStart(2,"0")).join("")}async request(e,t,n){let r=this.addQueryParams(e),o=await this.formatBody(n),s=await fetch(r,{method:t,headers:this.getHeaders(),body:o});if(this.digestAuth)s=await this.handleDigestAuth(s,r,t,n);let a=await s.json();return this.resetState(),new N(a,s.status,s.headers,s.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 $e=new J;_();import{path as k}from"@stacksjs/path";function G(e){if(!e||typeof e!=="object")return{type:"string"};let t=e,n=Array.isArray(t.rules)?t.rules:[],r=(m)=>n.find((g)=>g.name===m),o=(m,g)=>{let i=r(m)?.params?.[g];return typeof i==="number"?i:void 0},s=t.name??t._type??"string",a={type:s==="enum"?"string":s},c=o("min","min")??(typeof t._min==="number"?t._min:void 0),d=o("max","max")??(typeof t._max==="number"?t._max:void 0);if(c!==void 0)a[s==="string"?"minLength":"minimum"]=c;if(d!==void 0)a[s==="string"?"maxLength":"maximum"]=d;if(r("email")||t._email)a.format="email";if(r("url")||t._url)a.format="uri";if(r("uuid")||t._uuid)a.format="uuid";let l=Array.isArray(t.allowedValues)?t.allowedValues:Array.isArray(t._enum)?t._enum:null;if(l)a.enum=l;return a}function ge(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function Q(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={id:{type:"integer"}},n=["id"];if(e.traits?.useUuid)t.uuid={type:"string",format:"uuid"},n.push("uuid");for(let[r,o]of Object.entries(e.attributes??{})){if(o.hidden===!0)continue;let s=Q(r);if(t[s]=G(o.validation?.rule),o.required===!0)n.push(s)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let o=`${Q(r.trim())}_id`;t[o]??={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 be(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 Re(e,t){let n={...t},r=e?.responses;if(r&&typeof r==="object")for(let[s,a]of Object.entries(r)){let c=a;if(!c||typeof c!=="object"||typeof c.description!=="string")continue;n[String(s)]={description:c.description,...c.schema&&typeof c.schema==="object"?{content:{"application/json":{schema:c.schema}}}:{}}}let o=e?.responseHeaders;if(o&&typeof o==="object"){let s={};for(let[a,c]of Object.entries(o)){let d=c;if(!d||typeof d!=="object"||typeof d.description!=="string")continue;s[a]={description:d.description,...d.schema&&typeof d.schema==="object"?{schema:d.schema}:{}}}if(Object.keys(s).length>0)for(let a of Object.keys(n))n[a]={...n[a],headers:s}}return n}async function we(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 a=(await import(r)).default;return a&&typeof a==="object"?a:null}catch{}}catch{}return null}async function De(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router"),r=t?process.env.APP_ENV:void 0,o=t&&"APP_ENV"in process.env;if(t)process.env.APP_ENV="production";try{try{let{loadRoutes:i}=await import("@stacksjs/router"),{default:u}=await import(k.appPath("Routes.ts"));await i(u)}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${u}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${u}`)}try{try{await import("@stacksjs/orm/routes")}catch{await Promise.resolve().then(() => (I(),{}))}}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${u}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${u}`)}}finally{if(t)if(o)process.env.APP_ENV=r;else delete process.env.APP_ENV}let s={};try{let u;try{u=await import("@stacksjs/orm/model-registry")}catch{u=await Promise.resolve().then(() => (z(),W))}s=await u.loadModelRegistry({defaultsRoot:k.storagePath("framework/defaults/app/Models"),userRoot:k.projectPath("app/Models")})}catch(i){let u=i instanceof Error?i.message:String(i);if(t)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${u}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${u}`)}let a=(i)=>i.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),c=[...n()].map((i)=>({route:i,oasPath:a(i.path),method:i.method.toLowerCase()})).sort((i,u)=>{if(i.oasPath!==u.oasPath)return i.oasPath<u.oasPath?-1:1;return i.method<u.method?-1:i.method>u.method?1:0});if(t&&c.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 d="Stacks API";if(!t)try{let{config:i}=await import("@stacksjs/config");if(i.app?.name)d=`${i.app.name} API`}catch{}let l={openapi:"3.0.0",info:{title:d,version:"1.0.0"},paths:{},components:{schemas:{}}},m=Object.values(s).map((i)=>({name:String(i.name),path:be(i),schema:ye(i)})).filter((i)=>i.path!==null).sort((i,u)=>i.name<u.name?-1:i.name>u.name?1:0);for(let i of m)l.components.schemas[i.name]=i.schema;let g=new Set;for(let{route:i,oasPath:u,method:p}of c){if(!l.paths[u])l.paths[u]={};let O=[];for(let h of i.path.matchAll(/\{(\w+)\}/g))if(h[1])O.push(h[1]);for(let h of i.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(h[1])O.push(h[1]);let P=i.name??`${p}_${u.replace(/[^a-z0-9]/gi,"_")}`,j=P;if(g.has(j)){j=`${P}_${p}`;let h=2;while(g.has(j))j=`${P}_${p}_${h++}`}g.add(j);let b={summary:i.name??i.path,operationId:j,parameters:O.map((h)=>({name:h,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"}}},T=m.find((h)=>u===h.path||u===`${h.path}/{id}`);if(T){let h=u===T.path&&p==="get"?{type:"array",items:T.schema}:T.schema;if(b.responses[200].content={"application/json":{schema:{type:"object",properties:{data:h},required:["data"]}}},p==="post"&&u===T.path)b.responses[201]={...b.responses[200],description:"Created"},delete b.responses[200]}let q=i.action??(i.handler?await we(i.handler):null),B=q&&typeof q.validations==="object"&&q.validations!==null?q.validations:null;b.responses=Re(q,b.responses);let C=q?.requestHeaders;if(C&&typeof C==="object")for(let[h,R]of Object.entries(C)){let f=R;if(!f||typeof f!=="object"||typeof f.description!=="string")continue;b.parameters?.push({name:h,in:"header",description:f.description,required:f.required===!0,schema:f.schema&&typeof f.schema==="object"?f.schema:{type:"string"}})}if(B&&Object.keys(B).length>0){let h=Object.entries(B).map(([R,f])=>{let A=f?.rule;return{field:R,schema:G(A),required:ge(A)}});if(p==="get"||p==="head"||p==="delete"){let R=new Set(O);for(let{field:f,schema:A,required:S}of h){if(R.has(f))continue;b.parameters?.push({name:f,in:"query",required:S,schema:A})}}else{let R={type:"object",properties:{},required:[]},{properties:f,required:A}=R;for(let S of h)if(f[S.field]=S.schema,S.required)A.push(S.field);if(A.length===0)delete R.required;b.requestBody={required:A.length>0,content:{"application/json":{schema:R}}}}}l.paths[u][p]=b}if(e.write!==!1){await Bun.write(k.frameworkPath("api/openapi.json"),JSON.stringify(l,null,2));await Promise.resolve().then(() => D());await Promise.resolve().then(() => _());await Bun.write(k.frameworkPath("api/api-types.ts"),M(l)),await Bun.write(k.frameworkPath("api/client.ts"),H(l,{name:l.info.title}))}return l}D();class y{static instance=new y;isMissing(){return!0}}class v{data;constructor(e){this.data=e}}class Z{condition;value;defaultValue;constructor(e,t,n=new y){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class X{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 E(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:y.instance}whenNotNull(e,t){if(e===null||e===void 0)return y.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:y.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:y.instance}merge(e){return new v(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return y.instance;let r=typeof t==="function"?t():t;return new v(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=X.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,o]of Object.entries(e)){if(o instanceof y)continue;if(o instanceof v){Object.assign(n,this.filterAndResolve(o.data,t+1));continue}if(o instanceof Z){let s=o.resolve();if(!(s instanceof y))n[r]=s;continue}if(o!==null&&typeof o==="object"&&!Array.isArray(o)&&!(o instanceof Date)){n[r]=this.filterAndResolve(o,t+1);continue}if(Array.isArray(o)){n[r]=o.filter((s)=>!(s instanceof y)).map((s)=>{if(s instanceof v)return s.data;if(s!==null&&typeof s==="object"&&!(s instanceof Date))return this.filterAndResolve(s,t+1);return s});continue}n[r]=o}return n}static withoutWrapping(){this.wrap=null}static wrapWith(e){this.wrap=e}}class E{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 K extends E{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:o,total:s,baseUrl:a=""}=n,c=Math.ceil(s/o),d=s>0?(r-1)*o+1:null,l=s>0?Math.min(r*o,s):null;return new K({data:e,meta:{current_page:r,from:d,last_page:c,per_page:o,to:l,total:s},links:{first:`${a}?page=1`,last:`${a}?page=${c}`,prev:r>1?`${a}?page=${r-1}`:null,next:r<c?`${a}?page=${r+1}`:null}},t)}toResponse(e){return{data:this.resolve(e),meta:this.meta,links:this.links,...this.additional}}}function Ce(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function _e(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{Z as ConditionalValue,X as JsonResource,v as MergeValue,y as MissingValue,K as PaginatedResourceCollection,E as ResourceCollection,_e as collection,Re as describedResponses,$e as fetcher,De as generateOpenApi,ce as methodName,ye as modelDefinitionToSchema,H as renderApiClient,M as renderOpenApiTypes,Ce as resource,ge as ruleIsRequired,G as ruleToSchema,w 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.74.53",
5
+ "version": "0.74.56",
6
6
  "description": "The Stacks API utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -61,15 +61,15 @@
61
61
  "prepublishOnly": "bun run build"
62
62
  },
63
63
  "dependencies": {
64
- "@stacksjs/config": "0.74.53",
65
- "@stacksjs/path": "0.74.53"
64
+ "@stacksjs/config": "0.74.56",
65
+ "@stacksjs/path": "0.74.56"
66
66
  },
67
67
  "devDependencies": {
68
- "@stacksjs/utils": "0.74.53",
68
+ "@stacksjs/utils": "0.74.56",
69
69
  "better-dx": "^0.2.24"
70
70
  },
71
71
  "peerDependencies": {
72
- "@stacksjs/router": "0.74.53"
72
+ "@stacksjs/router": "0.74.56"
73
73
  },
74
74
  "peerDependenciesMeta": {
75
75
  "@stacksjs/router": {