@stacksjs/api 0.75.514 → 0.75.518
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/digest.js +1 -1
- package/dist/fetcher.js +1 -1
- package/dist/generate-client.js +4 -4
- package/dist/generate-openapi.js +1 -1
- package/dist/generate-types.js +11 -11
- package/dist/query.js +1 -1
- package/dist/resource.js +1 -1
- package/package.json +6 -6
package/dist/digest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{md5,sha256}from"hash-wasm";function digestChallenges(header){const parts=[];let quoted
|
|
1
|
+
import{md5,sha256}from"hash-wasm";function digestChallenges(header){const parts=[];let quoted=false;let escaped=false;let start=0;for(let index=0;index<header.length;index++){const char=header[index];if(escaped){escaped=false;continue}if(quoted&&char==="\\"){escaped=true;continue}if(char==='"')quoted=!quoted;if(char===","&&!quoted){parts.push(header.slice(start,index));start=index+1}}if(quoted||escaped)return[];parts.push(header.slice(start));const challenges=[];let current;for(let part of parts){part=part.trim();const scheme=/^([a-z][a-z0-9_-]*)[ \t]+(?=[^ \t=])/i.exec(part);if(scheme){current=scheme[1].toLowerCase()==="digest"?Object.create(null):undefined;if(current)challenges.push(current);part=part.slice(scheme[0].length)}if(!current)continue;const parameter=/^([a-z][a-z0-9_-]*)\s*=\s*("(?:\\.|[^"\\])*"|[^\s]+)$/i.exec(part);if(!parameter){current=undefined;challenges.pop();continue}const key=parameter[1].toLowerCase();if(key in current){current=undefined;challenges.pop();continue}const raw=parameter[2];current[key]=raw.startsWith('"')?raw.slice(1,-1).replace(/\\(.)/g,"$1"):raw}return challenges}export async function digestAuthorization(header,credentials,method,url,body){const candidates=digestChallenges(header).filter((challenge)=>/^(?:MD5|SHA-256)(?:-sess)?$/i.test(challenge.algorithm??"MD5")).sort((a,b)=>Number(/^SHA-256/i.test(b.algorithm??""))-Number(/^SHA-256/i.test(a.algorithm??"")));for(const challenge of candidates){if(challenge.realm===undefined||!challenge.nonce)continue;if(challenge.charset&&challenge.charset.toUpperCase()!=="UTF-8")continue;const user=challenge.charset?credentials.username.normalize("NFC"):credentials.username;const password=challenge.charset?credentials.password.normalize("NFC"):credentials.password;const offered=challenge.qop?.split(",").map((value)=>value.trim().toLowerCase());const qop=offered?.includes("auth")?"auth":offered?.includes("auth-int")?"auth-int":undefined;if(offered&&!qop)continue;const algorithm=(challenge.algorithm??"MD5").toUpperCase();const session=algorithm.endsWith("-SESS");const base=algorithm.startsWith("SHA-256")?"SHA-256":"MD5";const hash=base==="MD5"?md5:sha256;const quote=(value)=>`"${value.replace(/[\\"]/g,"\\$&")}"`;const cnonce=Array.from(crypto.getRandomValues(new Uint8Array(16)),(value)=>value.toString(16).padStart(2,"0")).join("");const nonceCount="00000001";const target=new URL(url);const uri=target.pathname+target.search;let ha1=await hash(`${user}:${challenge.realm}:${password}`);if(session)ha1=await hash(`${ha1}:${challenge.nonce}:${cnonce}`);const ha2=await hash(`${method}:${uri}${qop==="auth-int"?`:${await hash(body)}`:""}`);const response=await hash(qop?`${ha1}:${challenge.nonce}:${nonceCount}:${cnonce}:${qop}:${ha2}`:`${ha1}:${challenge.nonce}:${ha2}`);const username=challenge.userhash?.toLowerCase()==="true"?await hash(`${user}:${challenge.realm}`):user;const encodedUsername=encodeURIComponent(username).replace(/['()*]/g,(char)=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`);const usernameField=/[^\x20-\x7E]/.test(username)?`username*=UTF-8''${encodedUsername}`:`username=${quote(username)}`;const fields=[usernameField,`realm=${quote(challenge.realm)}`,`nonce=${quote(challenge.nonce)}`,`uri=${quote(uri)}`,`algorithm=${base}${session?"-sess":""}`,`response=${quote(response)}`];if(qop)fields.push(`qop=${qop}`,`nc=${nonceCount}`);if(qop||session)fields.push(`cnonce=${quote(cnonce)}`);if(challenge.opaque!==undefined)fields.push(`opaque=${quote(challenge.opaque)}`);if(challenge.userhash?.toLowerCase()==="true")fields.push("userhash=true");return`Digest ${fields.join(", ")}`}return null}
|
package/dist/fetcher.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withQuery}from"./query";class FetcherResponseImpl{data;status;headers;isOk;constructor(data,status,headers,isOk){this.data=data;this.status=status;this.headers=headers;this.isOk=isOk}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 Fetcher{defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData
|
|
1
|
+
import{withQuery}from"./query";class FetcherResponseImpl{data;status;headers;isOk;constructor(data,status,headers,isOk){this.data=data;this.status=status;this.headers=headers;this.isOk=isOk}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 Fetcher{defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=false;customHeaders={};attachments=[];isMultipart=false;digestAuth;withQueryParams(params){this.queryParams=params;return this}withHeaders(headers){for(const[name,value]of Object.entries(headers))this.customHeaders[name.toLowerCase()]=value;return this}accept(contentType){this.defaultHeaders.Accept=contentType;return this}acceptJson(){return this.accept("application/json")}withToken(token){this.customHeaders.authorization=`Bearer ${token}`;return this}withBasicAuth(username,password){const credentials=btoa(`${username}:${password}`);this.customHeaders.authorization=`Basic ${credentials}`;return this}withDigestAuth(username,password){this.digestAuth={username,password};return this}withBody(data){this.bodyData=data;return this}asForm(){this.isFormData=true;this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded";return this}attach(name,content,filename,headers){const blobContent=typeof content==="string"?new Blob([content],{type:headers?.["Content-Type"]||"text/plain"}):content;this.attachments.push({name,content:blobContent,filename,headers});this.isMultipart=true;delete this.defaultHeaders["Content-Type"];return this}getHeaders(){const headers=new Headers(this.defaultHeaders);for(const[name,value]of Object.entries(this.customHeaders))headers.set(name,value);return headers}addQueryParams(url){if(!this.queryParams)return url;return withQuery(url,this.queryParams)}async formatBody(body){const finalBody=body||this.bodyData;if(this.isMultipart){const formData=new FormData;if(finalBody){Object.entries(finalBody).forEach(([key,value])=>{formData.append(key,String(value))})}for(const attachment of this.attachments){if(attachment.headers){const blob=attachment.content instanceof Blob?new Blob([attachment.content],{type:attachment.headers["Content-Type"]}):attachment.content;formData.append(attachment.name,blob,attachment.filename)}else{formData.append(attachment.name,attachment.content,attachment.filename)}}return formData}if(this.isFormData&&finalBody){const formData=new URLSearchParams;Object.entries(finalBody).forEach(([key,value])=>{if(value!=null)formData.append(key,String(value))});return formData.toString()}return finalBody?JSON.stringify(finalBody):undefined}resetState(){this.queryParams=undefined;this.bodyData=undefined;this.isFormData=false;this.isMultipart=false;this.customHeaders={};this.attachments=[];this.digestAuth=undefined;this.defaultHeaders={Accept:"application/json","Content-Type":"application/json"}}request(url,method,body){const owned=new Fetcher;Object.assign(owned,this,{defaultHeaders:{...this.defaultHeaders},customHeaders:{...this.customHeaders},attachments:[...this.attachments],digestAuth:this.digestAuth?{...this.digestAuth}:undefined});this.resetState();return owned.perform(url,method,body)}async perform(url,method,body){const urlWithParams=this.addQueryParams(url);const formattedBody=await this.formatBody(body);const headers=this.getHeaders();if(this.isMultipart)headers.delete("content-type");const prepared=new Request(urlWithParams,{method,headers,body:formattedBody});let response;if(this.digestAuth){const bytes=prepared.body?new Uint8Array(await prepared.arrayBuffer()):undefined;const send=(requestHeaders)=>fetch(prepared.url,{method,headers:requestHeaders,body:bytes,credentials:"omit"});response=await send(prepared.headers);const target=new URL(prepared.url);target.hash="";const respondedAt=new URL(response.url);respondedAt.hash="";if(response.status===401&&respondedAt.href===target.href){const challenge=response.headers.get("www-authenticate");if(challenge){const{digestAuthorization}=await import("./digest");const authorization=await digestAuthorization(challenge,this.digestAuth,method,target.href,bytes??new Uint8Array);if(authorization){await response.body?.cancel();const authenticated=new Headers(prepared.headers);authenticated.set("authorization",authorization);response=await send(authenticated)}}}}else{response=await fetch(prepared)}const text=await response.text();const contentType=response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()??"";const json=contentType==="application/json"||contentType.endsWith("+json");const data=text===""?null:json?JSON.parse(text):text;this.resetState();return new FetcherResponseImpl(data,response.status,response.headers,response.ok)}async get(url){return this.request(url,"GET")}async post(url,body){return this.request(url,"POST",body)}async put(url,body){return this.request(url,"PUT",body)}async patch(url,body){return this.request(url,"PATCH",body)}async delete(url){return this.request(url,"DELETE")}}export const fetcher=new Fetcher;
|
package/dist/generate-client.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";import{clientRuntime}from"./client-runtime";import{operationParameters,renderSchemaComponents,resolveOpenApiReference,schemaType}from"./generate-types";const METHODS=["get","put","post","delete","options","head","patch"];export function methodName(operationId){const parts=operationId.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean)
|
|
1
|
+
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";import{clientRuntime}from"./client-runtime";import{operationParameters,renderSchemaComponents,resolveOpenApiReference,schemaType}from"./generate-types";const METHODS=["get","put","post","delete","options","head","patch"];export function methodName(operationId){const parts=operationId.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean);const trimmed=parts[0]?.toLowerCase()==="api"?parts.slice(1):parts[1]?.toLowerCase()==="api"?[parts[0],...parts.slice(2)]:parts;const[first,...rest]=trimmed;if(!first)return"call";const head=first.charAt(0).toLowerCase()+first.slice(1);const tail=rest.map((part)=>part.charAt(0).toUpperCase()+part.slice(1));const name=[head,...tail].join("");return/^[a-z_$]/i.test(name)?name:`call${name.charAt(0).toUpperCase()}${name.slice(1)}`}function successType(operation,document,method){if(method==="head")return"null";const types=[];for(const[status,entry]of Object.entries(operation.responses??{})){if(!/^2(?:\d\d|XX)$/i.test(status))continue;const response=resolveOpenApiReference(entry,document);if(status==="204"||status==="205"||!Object.keys(response.content??{}).length)types.push("null");else for(const media of Object.values(response.content??{}))types.push(schemaType(media.schema,{document,direction:"response"}))}return types.includes("unknown")?"unknown":[...new Set(types)].join(" | ")||"unknown"}function comment(lines,indent=" "){const kept=lines.filter(Boolean).flatMap((line)=>line.replace(/\*\//g,"*\\/").split(/\r?\n/));return kept.length?`${indent}/**
|
|
2
2
|
${kept.map((line)=>`${indent} * ${line}`).join(`
|
|
3
3
|
`)}
|
|
4
4
|
${indent} */
|
|
5
|
-
`:""}function renderOperation(route,method,operation,item,name,document){const parameters=operationParameters(item,operation,document)
|
|
5
|
+
`:""}function renderOperation(route,method,operation,item,name,document){const parameters=operationParameters(item,operation,document);const body=operation.requestBody&&resolveOpenApiReference(operation.requestBody,document);const pathAndQuery=parameters.filter((parameter)=>parameter.in==="path"||parameter.in==="query");const names=pathAndQuery.map((parameter)=>parameter.name);const grouped=new Set(names).size!==names.length||Boolean(body)&&names.includes("body")||parameters.some((parameter)=>parameter.in==="header")&&names.includes("headers");const descriptors=parameters.map((parameter)=>{const styles=parameter.in==="query"?["form","deepObject","spaceDelimited","pipeDelimited"]:["simple"];if(!["path","query","header"].includes(parameter.in)||parameter.style&&!styles.includes(parameter.style))throw new TypeError(`Unsupported parameter serialization: ${parameter.in} ${parameter.style??""}`);return{name:parameter.name,in:parameter.in,required:parameter.in==="path"||Boolean(parameter.required),...parameter.in==="header"?{group:"headers"}:grouped?{group:parameter.in}:{},...parameter.style?{style:parameter.style}:{},...parameter.explode!==undefined?{explode:parameter.explode}:{}}});const fields=[];const required=(parameter)=>parameter.in==="path"||parameter.required;const field=(parameter)=>`${JSON.stringify(parameter.name)}${required(parameter)?"":"?"}: ${schemaType(parameter.schema,{document,direction:"request"})}`;if(!grouped)fields.push(...pathAndQuery.map(field));for(const location of[...grouped?["path","query"]:[],"header"]){const entries=parameters.filter((parameter)=>parameter.in===location);if(entries.length)fields.push(`${location==="header"?"headers":location}${entries.some(required)?"":"?"}: { ${entries.map(field).join("; ")} }`)}const content=Object.keys(body?.content??{});if(body&&!content.length)throw new TypeError("Request body must declare a media type");if(body){const bodyTypes=Object.entries(body.content??{}).map(([type,media])=>{const shape=schemaType(media.schema,{document,direction:"request"});return type==="multipart/form-data"?`${shape} | FormData`:shape});fields.push(`body${body.required?"":"?"}: ${[...new Set(bodyTypes)].join(" | ")}`)}const everyFieldOptional=!parameters.some(required)&&!body?.required;const argument=fields.length?`input${everyFieldOptional?"?":""}: { ${fields.join("; ")} }, `:"";const documentation=comment([operation.summary&&operation.summary!==route?operation.summary:`${method.toUpperCase()} ${route}`,operation.description??""]);const accept=[...new Set(Object.values(operation.responses??{}).flatMap((entry)=>Object.keys(resolveOpenApiReference(entry,document).content??{})))].join(", ")||"application/json";const binary=[...new Set(Object.values(operation.responses??{}).flatMap((entry)=>Object.entries(resolveOpenApiReference(entry,document).content??{}).filter(([,media])=>{const schema=resolveOpenApiReference(media.schema??{},document);return schema.type==="string"&&schema.format==="binary"}).map(([type])=>type.split(";")[0].trim().toLowerCase())))];return`${documentation} ${name}(${argument}options?: RequestOptions): Promise<ApiResult<${successType(operation,document,method)}>> {
|
|
6
6
|
return request(config, ${JSON.stringify(method.toUpperCase())}, ${JSON.stringify(route)}, ${fields.length?"input ?? {}":"{}"}, ${JSON.stringify(descriptors)}, ${body?JSON.stringify({required:Boolean(body.required),content}):"null"}, ${JSON.stringify(accept)}, ${JSON.stringify(binary)}, options)
|
|
7
|
-
},`}export function renderApiClient(document,options={}){const operations=Object.entries(document.paths??{}).flatMap(([route,item])=>METHODS.flatMap((method)=>{const operation=item[method];return operation?[{route,item,method,operation,preferred:methodName(operation.operationId??`${method}_${route}`)}]:[]}))
|
|
7
|
+
},`}export function renderApiClient(document,options={}){const operations=Object.entries(document.paths??{}).flatMap(([route,item])=>METHODS.flatMap((method)=>{const operation=item[method];return operation?[{route,item,method,operation,preferred:methodName(operation.operationId??`${method}_${route}`)}]:[]}));const reserved=new Set(["config","then","constructor","prototype","__proto__"]);const preferred=new Set(operations.map((operation)=>operation.preferred));const used=new Set(reserved);const methods=operations.map((entry)=>{let name=entry.preferred;let suffix=2;if(used.has(name)){do{name=`${entry.preferred}${suffix++}`}while(used.has(name)||preferred.has(name))}used.add(name);return renderOperation(entry.route,entry.method,entry.operation,entry.item,name,document)});return`/* eslint-disable */
|
|
8
8
|
${comment([`${options.name??"API"} client, generated from OpenAPI.`,"Do not edit; run buddy generate:openapi.","No imports or dependencies."],"")}
|
|
9
9
|
${clientRuntime}
|
|
10
10
|
${renderSchemaComponents(document)}
|
|
@@ -18,4 +18,4 @@ ${methods.join(`
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
export type Client = ReturnType<typeof createClient>
|
|
21
|
-
`}if(
|
|
21
|
+
`}if(require.main==require.module){const apiRoot=resolve(import.meta.dir,"../../../api");const input=resolve(process.argv[2]||resolve(apiRoot,"openapi.json"));const output=resolve(process.argv[3]||resolve(apiRoot,"client.ts"));const document=JSON.parse(readFileSync(input,"utf8"));writeFileSync(output,renderApiClient(document));console.log(`Generated ${output}`)}
|
package/dist/generate-openapi.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{path}from"@stacksjs/path";export function ruleToSchema(rule){if(!rule||typeof rule!=="object")return{type:"string"};const r=rule,rules=Array.isArray(r.rules)?r.rules:[],named=(name)=>rules.find((entry)=>entry.name===name),parameter=(name,key)=>{const value=named(name)?.params?.[key];return typeof value==="number"?value:void 0},type=r.name??r._type??"string",out={type:type==="enum"?"string":type},min=parameter("min","min")??(typeof r._min==="number"?r._min:void 0),max=parameter("max","max")??(typeof r._max==="number"?r._max:void 0);if(min!==void 0)out[type==="string"?"minLength":"minimum"]=min;if(max!==void 0)out[type==="string"?"maxLength":"maximum"]=max;if(named("email")||r._email)out.format="email";if(named("url")||r._url)out.format="uri";if(named("uuid")||r._uuid)out.format="uuid";const allowed=Array.isArray(r.allowedValues)?r.allowedValues:Array.isArray(r._enum)?r._enum:null;if(allowed)out.enum=allowed;return out}export function ruleIsRequired(rule){if(!rule||typeof rule!=="object")return!1;const r=rule;return Boolean(r.isRequired??r._required)}function snakeCase(value){return value.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}export function modelDefinitionToSchema(model){const properties={id:{type:"integer"}},required=["id"];if(model.traits?.useUuid){properties.uuid={type:"string",format:"uuid"};required.push("uuid")}for(const[name,attribute]of Object.entries(model.attributes??{})){if(attribute.hidden===!0)continue;const key=snakeCase(name);properties[key]=ruleToSchema(attribute.validation?.rule);if(attribute.required===!0)required.push(key)}for(const relation of model.belongsTo??[]){if(typeof relation!=="string"||!relation.trim())continue;const key=`${snakeCase(relation.trim())}_id`;properties[key]??={type:"integer"}}if(model.traits?.useTimestamps!==!1){properties.created_at={type:"string",format:"date-time"};properties.updated_at={type:"string",format:"date-time"}}if(model.traits?.useSoftDeletes)properties.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties,required:[...new Set(required)]}}function modelApiPath(model){const api=model.traits?.useApi;if(!api||typeof api!=="object"||!api.uri)return null;const prefix=String(api.prefix||"").replace(/^\/+|\/+$/g,""),uri=String(api.uri).replace(/^\/+|\/+$/g,"");return`/api/${prefix?`${prefix}/`:""}${uri}`}export function describedResponses(action,base){const responses={...base},documented=action?.responses;if(documented&&typeof documented==="object")for(const[status,answer]of Object.entries(documented)){const shape=answer;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;responses[String(status)]={description:shape.description,...shape.schema&&typeof shape.schema==="object"?{content:{"application/json":{schema:shape.schema}}}:{}}}const headers=action?.responseHeaders;if(headers&&typeof headers==="object"){const described={};for(const[name,header]of Object.entries(headers)){const shape=header;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;described[name]={description:shape.description,...shape.schema&&typeof shape.schema==="object"?{schema:shape.schema}:{}}}if(Object.keys(described).length>0)for(const status of Object.keys(responses))responses[status]={...responses[status],headers:described}}return responses}async function loadAction(handlerPath){if(typeof handlerPath!=="string"||!handlerPath||handlerPath.includes(".."))return null;try{const{path:p}=await import("@stacksjs/path"),candidates=[p.appPath(`${handlerPath}.ts`),p.defaultsPath(`app/${handlerPath}.ts`)];for(const candidate of candidates)try{if(!await Bun.file(candidate).exists())continue;const action=(await import(candidate)).default;return action&&typeof action==="object"?action:null}catch{}}catch{}return null}export async function generateOpenApi(options={}){const portable=options.portable??!0,{listRegisteredRoutes}=await import("@stacksjs/router"),pinnedEnv=portable?process.env.APP_ENV:void 0,hadPinnedEnv=portable&&"APP_ENV"in process.env;if(portable)process.env.APP_ENV="production";try{try{const{appRouteRegistry,loadRoutes}=await import("@stacksjs/router");await loadRoutes(await appRouteRegistry())}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${message}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${message}`)}try{const ormRoutesPackage="@stacksjs/orm/routes";try{await import(ormRoutesPackage)}catch{await import("../../orm/routes")}}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${message}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${message}`)}}finally{if(portable)if(hadPinnedEnv)process.env.APP_ENV=pinnedEnv;else delete process.env.APP_ENV}let modelRegistry={};try{const registryPackage="@stacksjs/orm/model-registry";let registryModule;try{registryModule=await import(registryPackage)}catch{registryModule=await import("../../orm/src/model-registry")}const registry=await registryModule.loadModelRegistryWithOrigins({defaultsRoot:path.defaultsPath("app/Models"),userRoot:path.projectPath("app/Models")});let securityApi;try{securityApi=(await import(path.projectPath("config/security.ts"))).default?.api}catch{}const selection=registryModule.resolveModelApiSelection(securityApi?.models,process.env.STACKS_MODEL_APIS);modelRegistry=registryModule.selectApiModels(registry,selection).models}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${message}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${message}`)}const toOasPath=(p)=>p.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),routes=[...listRegisteredRoutes()].map((route)=>({route,oasPath:toOasPath(route.path),method:route.method.toLowerCase()})).sort((a,b)=>{if(a.oasPath!==b.oasPath)return a.oasPath<b.oasPath?-1:1;return a.method<b.method?-1:a.method>b.method?1:0});if(portable&&routes.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 appName="Stacks API";if(!portable)try{const{config}=await import("@stacksjs/config");if(config.app?.name)appName=`${config.app.name} API`}catch{}const spec={openapi:"3.0.0",info:{title:appName,version:"1.0.0"},paths:{},components:{schemas:{}}},modelApis=Object.values(modelRegistry).map((model)=>({name:String(model.name),path:modelApiPath(model),schema:modelDefinitionToSchema(model)})).filter((entry)=>entry.path!==null).sort((left,right)=>left.name<right.name?-1:left.name>right.name?1:0);for(const model of modelApis)spec.components.schemas[model.name]=model.schema;const operationIds=new Set;for(const{route:r,oasPath,method}of routes){if(!spec.paths[oasPath])spec.paths[oasPath]={};const paramNames=[];for(const m of r.path.matchAll(/\{(\w+)\}/g))if(m[1])paramNames.push(m[1]);for(const m of r.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(m[1])paramNames.push(m[1]);const preferredOperationId=r.name??`${method}_${oasPath.replace(/[^a-z0-9]/gi,"_")}`;let operationId=preferredOperationId;if(operationIds.has(operationId)){operationId=`${preferredOperationId}_${method}`;let suffix=2;while(operationIds.has(operationId))operationId=`${preferredOperationId}_${method}_${suffix++}`}operationIds.add(operationId);const op={summary:r.name??r.path,operationId,parameters:paramNames.map((name)=>({name,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"}}},modelApi=modelApis.find((model)=>oasPath===model.path||oasPath===`${model.path}/{id}`);if(modelApi){const dataSchema=oasPath===modelApi.path&&method==="get"?{type:"array",items:modelApi.schema}:modelApi.schema;op.responses[200].content={"application/json":{schema:{type:"object",properties:{data:dataSchema},required:["data"]}}};if(method==="post"&&oasPath===modelApi.path){op.responses[201]={...op.responses[200],description:"Created"};delete op.responses[200]}}const action=r.action??(r.handler?await loadAction(r.handler):null),validations=action&&typeof action.validations==="object"&&action.validations!==null?action.validations:null;op.responses=describedResponses(action,op.responses);const requestHeaders=action?.requestHeaders;if(requestHeaders&&typeof requestHeaders==="object")for(const[name,header]of Object.entries(requestHeaders)){const shape=header;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;op.parameters?.push({name,in:"header",description:shape.description,required:shape.required===!0,schema:shape.schema&&typeof shape.schema==="object"?shape.schema:{type:"string"}})}if(validations&&Object.keys(validations).length>0){const fields=Object.entries(validations).map(([field,def])=>{const rule=def?.rule;return{field,schema:ruleToSchema(rule),required:ruleIsRequired(rule)}});if(method==="get"||method==="head"||method==="delete"){const taken=new Set(paramNames);for(const{field,schema,required}of fields){if(taken.has(field))continue;op.parameters?.push({name:field,in:"query",required,schema})}}else{const schema={type:"object",properties:{},required:[]},{properties:props,required}=schema;for(const field of fields){props[field.field]=field.schema;if(field.required)required.push(field.field)}if(required.length===0)delete schema.required;op.requestBody={required:required.length>0,content:{"application/json":{schema}}}}}spec.paths[oasPath][method]=op}if(options.write!==!1){await Bun.write(path.frameworkPath("api/openapi.json"),JSON.stringify(spec,null,2));const{renderOpenApiTypes}=await import("./generate-types"),{renderApiClient}=await import("./generate-client");await Bun.write(path.frameworkPath("api/api-types.ts"),renderOpenApiTypes(spec));await Bun.write(path.frameworkPath("api/client.ts"),renderApiClient(spec,{name:spec.info.title}))}return spec}
|
|
1
|
+
import{path}from"@stacksjs/path";export function ruleToSchema(rule){if(!rule||typeof rule!=="object")return{type:"string"};const r=rule;const rules=Array.isArray(r.rules)?r.rules:[];const named=(name)=>rules.find((entry)=>entry.name===name);const parameter=(name,key)=>{const value=named(name)?.params?.[key];return typeof value==="number"?value:undefined};const type=r.name??r._type??"string";const out={type:type==="enum"?"string":type};const min=parameter("min","min")??(typeof r._min==="number"?r._min:undefined);const max=parameter("max","max")??(typeof r._max==="number"?r._max:undefined);if(min!==undefined)out[type==="string"?"minLength":"minimum"]=min;if(max!==undefined)out[type==="string"?"maxLength":"maximum"]=max;if(named("email")||r._email)out.format="email";if(named("url")||r._url)out.format="uri";if(named("uuid")||r._uuid)out.format="uuid";const allowed=Array.isArray(r.allowedValues)?r.allowedValues:Array.isArray(r._enum)?r._enum:null;if(allowed)out.enum=allowed;return out}export function ruleIsRequired(rule){if(!rule||typeof rule!=="object")return false;const r=rule;return Boolean(r.isRequired??r._required)}function snakeCase(value){return value.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}export function modelDefinitionToSchema(model){const properties={id:{type:"integer"}};const required=["id"];if(model.traits?.useUuid){properties.uuid={type:"string",format:"uuid"};required.push("uuid")}for(const[name,attribute]of Object.entries(model.attributes??{})){if(attribute.hidden===true)continue;const key=snakeCase(name);properties[key]=ruleToSchema(attribute.validation?.rule);if(attribute.required===true)required.push(key)}for(const relation of model.belongsTo??[]){if(typeof relation!=="string"||!relation.trim())continue;const key=`${snakeCase(relation.trim())}_id`;properties[key]??={type:"integer"}}if(model.traits?.useTimestamps!==false){properties.created_at={type:"string",format:"date-time"};properties.updated_at={type:"string",format:"date-time"}}if(model.traits?.useSoftDeletes)properties.deleted_at={type:"string",format:"date-time",nullable:true};return{type:"object",properties,required:[...new Set(required)]}}function modelApiPath(model){const api=model.traits?.useApi;if(!api||typeof api!=="object"||!api.uri)return null;const prefix=String(api.prefix||"").replace(/^\/+|\/+$/g,"");const uri=String(api.uri).replace(/^\/+|\/+$/g,"");return`/api/${prefix?`${prefix}/`:""}${uri}`}export function describedResponses(action,base){const responses={...base};const documented=action?.responses;if(documented&&typeof documented==="object"){for(const[status,answer]of Object.entries(documented)){const shape=answer;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;responses[String(status)]={description:shape.description,...shape.schema&&typeof shape.schema==="object"?{content:{"application/json":{schema:shape.schema}}}:{}}}}const headers=action?.responseHeaders;if(headers&&typeof headers==="object"){const described={};for(const[name,header]of Object.entries(headers)){const shape=header;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;described[name]={description:shape.description,...shape.schema&&typeof shape.schema==="object"?{schema:shape.schema}:{}}}if(Object.keys(described).length>0){for(const status of Object.keys(responses))responses[status]={...responses[status],headers:described}}}return responses}async function loadAction(handlerPath){if(typeof handlerPath!=="string"||!handlerPath||handlerPath.includes(".."))return null;try{const{path:p}=await import("@stacksjs/path");const candidates=[p.appPath(`${handlerPath}.ts`),p.defaultsPath(`app/${handlerPath}.ts`)];for(const candidate of candidates){try{const file=Bun.file(candidate);if(!await file.exists())continue;const mod=await import(candidate);const action=mod.default;return action&&typeof action==="object"?action:null}catch{}}}catch{}return null}export async function generateOpenApi(options={}){const portable=options.portable??true;const{listRegisteredRoutes}=await import("@stacksjs/router");const pinnedEnv=portable?process.env.APP_ENV:undefined;const hadPinnedEnv=portable&&"APP_ENV"in process.env;if(portable)process.env.APP_ENV="production";try{try{const{appRouteRegistry,loadRoutes}=await import("@stacksjs/router");await loadRoutes(await appRouteRegistry())}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw new Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${message}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${message}`)}try{const ormRoutesPackage="@stacksjs/orm/routes";try{await import(ormRoutesPackage)}catch{await import("../../orm/routes")}}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw new Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${message}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${message}`)}}finally{if(portable){if(hadPinnedEnv)process.env.APP_ENV=pinnedEnv;else delete process.env.APP_ENV}}let modelRegistry={};try{const registryPackage="@stacksjs/orm/model-registry";let registryModule;try{registryModule=await import(registryPackage)}catch{registryModule=await import("../../orm/src/model-registry")}const registry=await registryModule.loadModelRegistryWithOrigins({defaultsRoot:path.defaultsPath("app/Models"),userRoot:path.projectPath("app/Models")});let securityApi;try{securityApi=(await import(path.projectPath("config/security.ts"))).default?.api}catch{}const selection=registryModule.resolveModelApiSelection(securityApi?.models,process.env.STACKS_MODEL_APIS);modelRegistry=registryModule.selectApiModels(registry,selection).models}catch(error){const message=error instanceof Error?error.message:String(error);if(portable)throw new Error(`[generateOpenApi] Refusing to emit model-free schemas: ${message}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${message}`)}const toOasPath=(p)=>p.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}");const routes=[...listRegisteredRoutes()].map((route)=>({route,oasPath:toOasPath(route.path),method:route.method.toLowerCase()})).sort((a,b)=>{if(a.oasPath!==b.oasPath)return a.oasPath<b.oasPath?-1:1;return a.method<b.method?-1:a.method>b.method?1:0});if(portable&&routes.length===0){throw new 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 appName="Stacks API";if(!portable){try{const{config}=await import("@stacksjs/config");if(config.app?.name)appName=`${config.app.name} API`}catch{}}const spec={openapi:"3.0.0",info:{title:appName,version:"1.0.0"},paths:{},components:{schemas:{}}};const modelApis=Object.values(modelRegistry).map((model)=>({name:String(model.name),path:modelApiPath(model),schema:modelDefinitionToSchema(model)})).filter((entry)=>entry.path!==null).sort((left,right)=>left.name<right.name?-1:left.name>right.name?1:0);for(const model of modelApis)spec.components.schemas[model.name]=model.schema;const operationIds=new Set;for(const{route:r,oasPath,method}of routes){if(!spec.paths[oasPath])spec.paths[oasPath]={};const paramNames=[];for(const m of r.path.matchAll(/\{(\w+)\}/g)){if(m[1])paramNames.push(m[1])}for(const m of r.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g)){if(m[1])paramNames.push(m[1])}const preferredOperationId=r.name??`${method}_${oasPath.replace(/[^a-z0-9]/gi,"_")}`;let operationId=preferredOperationId;if(operationIds.has(operationId)){operationId=`${preferredOperationId}_${method}`;let suffix=2;while(operationIds.has(operationId))operationId=`${preferredOperationId}_${method}_${suffix++}`}operationIds.add(operationId);const op={summary:r.name??r.path,operationId,parameters:paramNames.map((name)=>({name,in:"path",required:true,schema:{type:"string"}})),responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object"}}}},422:{description:"Validation failed"},500:{description:"Server error"}}};const modelApi=modelApis.find((model)=>oasPath===model.path||oasPath===`${model.path}/{id}`);if(modelApi){const dataSchema=oasPath===modelApi.path&&method==="get"?{type:"array",items:modelApi.schema}:modelApi.schema;op.responses[200].content={"application/json":{schema:{type:"object",properties:{data:dataSchema},required:["data"]}}};if(method==="post"&&oasPath===modelApi.path){op.responses[201]={...op.responses[200],description:"Created"};delete op.responses[200]}}const action=r.action??(r.handler?await loadAction(r.handler):null);const validations=action&&typeof action.validations==="object"&&action.validations!==null?action.validations:null;op.responses=describedResponses(action,op.responses);const requestHeaders=action?.requestHeaders;if(requestHeaders&&typeof requestHeaders==="object"){for(const[name,header]of Object.entries(requestHeaders)){const shape=header;if(!shape||typeof shape!=="object"||typeof shape.description!=="string")continue;op.parameters?.push({name,in:"header",description:shape.description,required:shape.required===true,schema:shape.schema&&typeof shape.schema==="object"?shape.schema:{type:"string"}})}}if(validations&&Object.keys(validations).length>0){const fields=Object.entries(validations).map(([field,def])=>{const rule=def?.rule;return{field,schema:ruleToSchema(rule),required:ruleIsRequired(rule)}});if(method==="get"||method==="head"||method==="delete"){const taken=new Set(paramNames);for(const{field,schema,required}of fields){if(taken.has(field))continue;op.parameters?.push({name:field,in:"query",required,schema})}}else{const schema={type:"object",properties:{},required:[]};const props=schema.properties;const required=schema.required;for(const field of fields){props[field.field]=field.schema;if(field.required)required.push(field.field)}if(required.length===0)delete schema.required;op.requestBody={required:required.length>0,content:{"application/json":{schema}}}}}spec.paths[oasPath][method]=op}if(options.write!==false){await Bun.write(path.frameworkPath("api/openapi.json"),JSON.stringify(spec,null,2));const{renderOpenApiTypes}=await import("./generate-types");const{renderApiClient}=await import("./generate-client");await Bun.write(path.frameworkPath("api/api-types.ts"),renderOpenApiTypes(spec));await Bun.write(path.frameworkPath("api/client.ts"),renderApiClient(spec,{name:spec.info.title}))}return spec}
|
package/dist/generate-types.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";const methods=["get","put","post","delete","options","head","patch","trace"];export function resolveOpenApiReference(value,document){const visited=new Set;let current=value;while(current&&typeof current==="object"&&"$ref"in current){const ref=current.$ref;if(!ref.startsWith("#/")||visited.has(ref))throw TypeError(`Unsupported or cyclic OpenAPI reference: ${ref}`);visited.add(ref);let target=document;for(const key of decodeURIComponent(ref.slice(2)).split("/").map((part)=>part.replace(/~1/g,"/").replace(/~0/g,"~"))){if(!target||typeof target!=="object"||!Object.hasOwn(target,key))throw TypeError(`Missing OpenAPI reference: ${ref}`);target=target[key]}current=target}if(!current||typeof current!=="object"||Array.isArray(current))throw TypeError("OpenAPI reference must resolve to an object");return current}export function operationParameters(item,operation,document){const parameters=new Map;for(const entry of[...item.parameters??[],...operation.parameters??[]]){const parameter=resolveOpenApiReference(entry,document)
|
|
1
|
+
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";const methods=["get","put","post","delete","options","head","patch","trace"];export function resolveOpenApiReference(value,document){const visited=new Set;let current=value;while(current&&typeof current==="object"&&"$ref"in current){const ref=current.$ref;if(!ref.startsWith("#/")||visited.has(ref))throw new TypeError(`Unsupported or cyclic OpenAPI reference: ${ref}`);visited.add(ref);let target=document;for(const key of decodeURIComponent(ref.slice(2)).split("/").map((part)=>part.replace(/~1/g,"/").replace(/~0/g,"~"))){if(!target||typeof target!=="object"||!Object.hasOwn(target,key))throw new TypeError(`Missing OpenAPI reference: ${ref}`);target=target[key]}current=target}if(!current||typeof current!=="object"||Array.isArray(current))throw new TypeError("OpenAPI reference must resolve to an object");return current}export function operationParameters(item,operation,document){const parameters=new Map;for(const entry of[...item.parameters??[],...operation.parameters??[]]){const parameter=resolveOpenApiReference(entry,document);const name=parameter.in==="header"?parameter.name.toLowerCase():parameter.name;parameters.set(`${parameter.in}:${name}`,parameter)}return[...parameters.values()]}function literal(value,ancestors=new Set){if(value===null)return"null";if(typeof value==="string")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return String(value);if(typeof value==="boolean")return String(value);if(!value||typeof value!=="object"||ancestors.has(value))throw new TypeError("OpenAPI enums must contain finite JSON values");ancestors.add(value);try{if(Array.isArray(value))return`[${value.map((item)=>literal(item,ancestors)).join(", ")}]`;return`{ ${Object.entries(value).map(([key,item])=>`${JSON.stringify(key)}: ${literal(item,ancestors)}`).join("; ")} }`}finally{ancestors.delete(value)}}function union(types){return types.includes("unknown")?"unknown":[...new Set(types)].join(" | ")||"never"}export function schemaType(schema,options={}){return renderSchema(schema,options,new Set)}function renderSchema(schema,options,ancestors){if(!schema)return"unknown";if(ancestors.has(schema))throw new TypeError("Recursive schemas must use component references");ancestors.add(schema);const render=(value)=>renderSchema(value,options,ancestors);try{if(schema.$ref){if(!options.document||!schema.$ref.startsWith("#/components/schemas/"))throw new TypeError(`Unsupported schema reference: ${schema.$ref}`);resolveOpenApiReference(schema,options.document);const pointer=decodeURIComponent(schema.$ref.slice("#/components/schemas/".length));if(pointer.includes("/"))return render(resolveOpenApiReference(schema,options.document));const name=pointer.replace(/~1/g,"/").replace(/~0/g,"~");return`components[${JSON.stringify(options.direction==="request"?"requestSchemas":"schemas")}][${JSON.stringify(name)}]`}if(schema.enum?.length)return union(schema.enum.map((value)=>literal(value)));let base;if(schema.type==="string")base=schema.format==="binary"?"Blob":"string";else if(schema.type==="number"||schema.type==="integer")base="number";else if(schema.type==="boolean")base="boolean";else if(schema.type==="null")base="null";else if(schema.type==="array")base=`Array<${render(schema.items)}>`;else if(schema.type==="object"||schema.properties||schema.additionalProperties!==undefined){const required=new Set(schema.required??[]);const properties=Object.entries(schema.properties??{}).filter(([,value])=>{const resolved=value.$ref&&options.document?resolveOpenApiReference(value,options.document):value;return!(options.direction==="request"&&resolved.readOnly)&&!(options.direction==="response"&&resolved.writeOnly)});const propertyTypes=properties.map(([name,value])=>({name,type:render(value),optional:!required.has(name)}));const fields=propertyTypes.map(({name,type,optional})=>`${JSON.stringify(name)}${optional?"?":""}: ${type}`);if(schema.additionalProperties){const extra=schema.additionalProperties===true?"unknown":render(schema.additionalProperties);const index=union([extra,...propertyTypes.map((field)=>field.type),...propertyTypes.some((field)=>field.optional)?["undefined"]:[]]);fields.push(`[key: string]: ${index}`)}base=fields.length?`{ ${fields.join("; ")} }`:schema.additionalProperties===false?"Record<string, never>":"Record<string, unknown>"}const composed=[];if(base)composed.push(base);for(const variants of[schema.oneOf,schema.anyOf]){if(variants?.length)composed.push(union(variants.map(render)))}if(schema.allOf?.length)composed.push(...schema.allOf.map(render));const result=composed.length>1?composed.map((type)=>`(${type})`).join(" & "):composed[0]??"unknown";return schema.nullable&&schema.type?union([result,"null"]):result}finally{ancestors.delete(schema)}}export function renderSchemaComponents(document){const map=(direction)=>Object.entries(document.components?.schemas??{}).map(([name,schema])=>` ${JSON.stringify(name)}: ${schemaType(schema,{document,direction})}`).join(`
|
|
2
2
|
`);return`export interface components {
|
|
3
3
|
schemas: {
|
|
4
4
|
${map("response")}
|
|
@@ -6,26 +6,26 @@ ${map("response")}
|
|
|
6
6
|
requestSchemas: {
|
|
7
7
|
${map("request")}
|
|
8
8
|
}
|
|
9
|
-
}`}function parameterGroups(parameters,document){return` parameters: {
|
|
10
|
-
${
|
|
9
|
+
}`}function parameterGroups(parameters,document){const groups=["query","header","path","cookie"].map((location)=>{const entries=parameters.filter((parameter)=>parameter.in===location);if(!entries.length)return` ${location}?: never`;const required=(parameter)=>parameter.in==="path"||parameter.required;const fields=entries.map((parameter)=>`${JSON.stringify(parameter.name)}${required(parameter)?"":"?"}: ${schemaType(parameter.schema,{document,direction:"request"})}`);return` ${location}${entries.every((parameter)=>!required(parameter))?"?":""}: { ${fields.join("; ")} }`});return` parameters: {
|
|
10
|
+
${groups.join(`
|
|
11
11
|
`)}
|
|
12
|
-
}`}function contentTypes(content,document,direction){if(!content||!Object.keys(content).length)return"never";return`{ ${Object.entries(content).map(([type,value])=>`${JSON.stringify(type)}: ${schemaType(value.schema,{document,direction})}`).join("; ")} }`}function renderOperation(item,operation,document){const body=operation.requestBody&&resolveOpenApiReference(operation.requestBody,document)
|
|
12
|
+
}`}function contentTypes(content,document,direction){if(!content||!Object.keys(content).length)return"never";return`{ ${Object.entries(content).map(([type,value])=>`${JSON.stringify(type)}: ${schemaType(value.schema,{document,direction})}`).join("; ")} }`}function renderOperation(item,operation,document){const body=operation.requestBody&&resolveOpenApiReference(operation.requestBody,document);const requestBody=body?`
|
|
13
13
|
requestBody${body.required?"":"?"}: { content: ${contentTypes(body.content,document,"request")} }`:`
|
|
14
|
-
requestBody?: never
|
|
14
|
+
requestBody?: never`;const responses=Object.entries(operation.responses??{}).map(([status,entry])=>{const response=resolveOpenApiReference(entry,document);return` ${JSON.stringify(status)}: { content: ${contentTypes(response.content,document,"response")} }`});return`{
|
|
15
15
|
${parameterGroups(operationParameters(item,operation,document),document)}${requestBody}
|
|
16
16
|
responses: {
|
|
17
17
|
${responses.join(`
|
|
18
18
|
`)}
|
|
19
19
|
}
|
|
20
|
-
}`}export function renderOpenApiTypes(document){
|
|
21
|
-
|
|
22
|
-
export interface paths {
|
|
23
|
-
${Object.entries(document.paths??{}).map(([route,item])=>{const operations=methods.map((method)=>{const operation=item[method];return operation?` ${method}: ${renderOperation(item,operation,document)}`:` ${method}?: never`});return` ${JSON.stringify(route)}: {
|
|
20
|
+
}`}export function renderOpenApiTypes(document){const paths=Object.entries(document.paths??{}).map(([route,item])=>{const operations=methods.map((method)=>{const operation=item[method];return operation?` ${method}: ${renderOperation(item,operation,document)}`:` ${method}?: never`});return` ${JSON.stringify(route)}: {
|
|
24
21
|
${operations.join(`
|
|
25
22
|
`)}
|
|
26
|
-
}`}).
|
|
23
|
+
}`});return`/** Generated from OpenAPI. Do not edit; run buddy generate:openapi. */
|
|
24
|
+
|
|
25
|
+
export interface paths {
|
|
26
|
+
${paths.join(`
|
|
27
27
|
`)}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
${renderSchemaComponents(document)}
|
|
31
|
-
`}if(
|
|
31
|
+
`}if(require.main==require.module){const apiRoot=resolve(import.meta.dir,"../../../api");const input=resolve(process.argv[2]||resolve(apiRoot,"openapi.json"));const output=resolve(process.argv[3]||resolve(apiRoot,"api-types.ts"));const document=JSON.parse(readFileSync(input,"utf8"));writeFileSync(output,renderOpenApiTypes(document));console.log(`Generated ${output}`)}
|
package/dist/query.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function withQuery(url,values,replace
|
|
1
|
+
export function withQuery(url,values,replace=false){const hashIndex=url.indexOf("#");const fragment=hashIndex<0?"":url.slice(hashIndex);const head=hashIndex<0?url:url.slice(0,hashIndex);const queryIndex=head.indexOf("?");const path=queryIndex<0?head:head.slice(0,queryIndex);const params=new URLSearchParams(queryIndex<0?"":head.slice(queryIndex+1));for(const[name,value]of Object.entries(values)){if(value!=null){if(replace)params.set(name,String(value));else params.append(name,String(value))}}const query=params.toString();return path+(query?`?${query}`:"")+fragment}
|
package/dist/resource.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toPaginator}from"@stacksjs/pagination";import{withQuery}from"./query";export class MissingValue{static instance=new MissingValue;isMissing(){return
|
|
1
|
+
import{toPaginator}from"@stacksjs/pagination";import{withQuery}from"./query";export class MissingValue{static instance=new MissingValue;isMissing(){return true}}export class MergeValue{data;constructor(data){this.data=data}}export class ConditionalValue{condition;value;defaultValue;constructor(condition,value,defaultValue=new MissingValue){this.condition=condition;this.value=value;this.defaultValue=defaultValue}resolve(){const shouldInclude=typeof this.condition==="function"?this.condition():this.condition;return shouldInclude?this.value:this.defaultValue}}const mergePayloads=new WeakMap;const MAX_RESOLVE_DEPTH=20;function resolveValue(value,request,context){if(value instanceof MissingValue||value===null||typeof value!=="object"||value instanceof Date)return value;if(context.depth>=MAX_RESOLVE_DEPTH)throw new RangeError("Resource serialization exceeded the maximum depth");if(context.ancestors.has(value))throw new TypeError("Resource serialization contains a cycle");context.ancestors.add(value);const next={depth:context.depth+1,ancestors:context.ancestors};try{if(value instanceof ConditionalValue)return resolveValue(value.resolve(),request,next);if(value instanceof MergeValue)return resolveValue(value.data,request,next);const merge=mergePayloads.get(value);if(merge)return resolveValue(merge,request,next);if(value instanceof JsonResource||value instanceof ResourceCollection)return value.resolveAt(request,next);if(Array.isArray(value)){const result=[];for(const item of value){const resolved=resolveValue(item,request,next);if(!(resolved instanceof MissingValue))result.push(resolved)}return result}if("toJSON"in value&&typeof value.toJSON==="function")return resolveValue(value.toJSON(),request,next);const entries=[];for(const[key,item]of Object.entries(value)){const resolved=resolveValue(item,request,next);if(resolved instanceof MissingValue)continue;if(item instanceof MergeValue||item!==null&&typeof item==="object"&&mergePayloads.has(item)){entries.push(...Object.entries(resolved))}else entries.push([key,resolved])}return Object.fromEntries(entries)}finally{context.ancestors.delete(value)}}export class JsonResource{resource;additional={};request;static wrap="data";static additionalMeta={};constructor(resource){this.resource=resource}withRequest(request){this.request=request;return this}withAdditional(data){this.additional={...this.additional,...data};return this}resolve(request){return resolveValue(this,request,{depth:0,ancestors:new WeakSet})}resolveAt(request,context){const req=request??this.request;return resolveValue(this.toArray(req),req,context)}toResponse(request){const data=this.resolve(request);const wrap=this.constructor.wrap;if(wrap){return{[wrap]:data,...this.additional}}return{...data,...this.additional}}toJson(request){return JSON.stringify(this.toResponse(request))}toJSON(){return this.toResponse()}static collection(resources){return new ResourceCollection(resources,this)}when(condition,value,defaultValue){const shouldInclude=typeof condition==="function"?condition():condition;if(shouldInclude){return typeof value==="function"?value():value}return defaultValue!==undefined?defaultValue:MissingValue.instance}whenNotNull(value,transform){if(value===null||value===undefined){return MissingValue.instance}return transform?transform(value):value}whenLoaded(relationship,value,defaultValue){const resource=this.resource;const isLoaded=relationship in resource&&resource[relationship]!==undefined;if(!isLoaded){return defaultValue!==undefined?defaultValue:MissingValue.instance}if(value!==undefined){return typeof value==="function"?value():value}return resource[relationship]}whenCounted(relationship,defaultValue){const resource=this.resource;const countKey=`${relationship}_count`;if(countKey in resource){return Number(resource[countKey])}return defaultValue!==undefined?defaultValue:MissingValue.instance}merge(data){const spreadable={...data};mergePayloads.set(spreadable,data);return spreadable}mergeWhen(condition,data){const shouldInclude=typeof condition==="function"?condition():condition;if(!shouldInclude){return MissingValue.instance}const resolvedData=typeof data==="function"?data():data;return this.merge(resolvedData)}static withoutWrapping(){this.wrap=null}static wrapWith(key){this.wrap=key}}export class ResourceCollection{resources;ResourceClass;additional={};request;static wrap="data";constructor(resources,ResourceClass){this.resources=resources;this.ResourceClass=ResourceClass}withRequest(request){this.request=request;return this}withAdditional(data){this.additional={...this.additional,...data};return this}resolve(request){return resolveValue(this,request,{depth:0,ancestors:new WeakSet})}resolveAt(request,context){const req=request??this.request;const resources=this.resources.map((resource)=>{const instance=new this.ResourceClass(resource);if(req)instance.withRequest(req);return instance});return resolveValue(resources,req,context)}toResponse(request){const data=this.resolve(request);const wrap=this.constructor.wrap;if(wrap){return{[wrap]:data,...this.additional}}return{data,...this.additional}}toJson(request){return JSON.stringify(this.toResponse(request))}toJSON(){return this.toResponse()}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}export class PaginatedResourceCollection extends ResourceCollection{meta;links;constructor(paginatedData,ResourceClass){super(paginatedData.data,ResourceClass);this.meta=paginatedData.meta;this.links=paginatedData.links}static fromPagination(data,ResourceClass,options){const{currentPage,perPage,total,baseUrl=""}=options;for(const[name,value]of Object.entries({currentPage,perPage,total})){if(!Number.isSafeInteger(value)||value<(name==="total"?0:1))throw new RangeError(`${name} must be a safe integer ${name==="total"?"at least zero":"greater than zero"}`)}const offset=(currentPage-1)*perPage;if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(offset+data.length)||data.length>perPage||data.length>0&&offset+data.length>total)throw new RangeError("Pagination rows do not fit the requested page and total");const page=toPaginator({data,meta:{page:currentPage,perPage,total,lastPage:Math.ceil(total/perPage)}});const link=(number)=>withQuery(baseUrl,{page:number},true);return new PaginatedResourceCollection({data,meta:{current_page:currentPage,from:page.from,last_page:page.last_page,per_page:perPage,to:page.to,total},links:{first:link(1),last:link(page.last_page),prev:currentPage>1?link(currentPage-1):null,next:page.has_more_pages?link(currentPage+1):null}},ResourceClass)}toResponse(request){const data=this.resolve(request);return{data,meta:this.meta,links:this.links,...this.additional}}}export function resource(data,transform){const transformed=transform(data);return{toResponse:()=>({data:transformed}),toJson:()=>JSON.stringify({data:transformed})}}export function collection(data,transform){const transformed=data.map(transform);return{toResponse:()=>({data:transformed}),toJson:()=>JSON.stringify({data:transformed})}}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/api",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.518",
|
|
6
6
|
"description": "The Stacks API utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -61,17 +61,17 @@
|
|
|
61
61
|
"prepublishOnly": "bun run build"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@stacksjs/config": "0.75.
|
|
65
|
-
"@stacksjs/path": "0.75.
|
|
66
|
-
"@stacksjs/pagination": "0.75.
|
|
64
|
+
"@stacksjs/config": "0.75.518",
|
|
65
|
+
"@stacksjs/path": "0.75.518",
|
|
66
|
+
"@stacksjs/pagination": "0.75.518",
|
|
67
67
|
"hash-wasm": "^4.12.0"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
-
"@stacksjs/utils": "0.75.
|
|
70
|
+
"@stacksjs/utils": "0.75.518",
|
|
71
71
|
"better-dx": "^0.2.24"
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
|
-
"@stacksjs/router": "0.75.
|
|
74
|
+
"@stacksjs/router": "0.75.518"
|
|
75
75
|
},
|
|
76
76
|
"peerDependenciesMeta": {
|
|
77
77
|
"@stacksjs/router": {
|