@m1212e/rumble 0.10.12 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -219,3 +219,55 @@ server.listen(3000, () => {
219
219
  });
220
220
 
221
221
  ```
222
+
223
+ ## Usage & client generation
224
+ You can use the GraphQL api with any client you like. However, rumble provides a generation api which can output a TypeScript client from a rumble instance. To perform a generation, use the exported function from your rumble instance like this:
225
+ ```ts
226
+
227
+ const { clientCreator } = rumble(...);
228
+
229
+ await clientCreator({
230
+ // where should the client files be generated to
231
+ outputPath: "./example/src/generated-client",
232
+ // where will the client be able to reach your api
233
+ apiUrl: "http://localhost:3000/graphql",
234
+
235
+ // in case you do not want to specify a url yourself
236
+ // or you would like to perform some customization
237
+ // to the underlying urql client, you can set
238
+
239
+ // useExternalUrqlClient: "../client"
240
+
241
+ // to point to your custom client
242
+ });
243
+ ```
244
+ > The client uses [urql](https://nearform.com/open-source/urql/docs/basics/core/) under the hood. If you would like more info on how the internals work, please see the docs.
245
+
246
+ An example usage might look like this:
247
+ ```ts
248
+ import { client } from "./generated-client/client";
249
+
250
+ const users = client.liveQuery.users({
251
+ id: true,
252
+ name: true,
253
+ });
254
+
255
+ users.subscribe((s) => s?.at(0));
256
+ ```
257
+ Notice how the client offers `liveQuery` in addition to the traditional `query`, `mutation` and `subscription` operations. The live query is a hybrid query and subscription which basically performs a regular query and then checks if there is a subscription available with the same name (as it is the case when using the rumble query implementation helpers). In case there is one present, it will also subscribe. If no subscription with the same name can be found, it will perform a regular query.
258
+
259
+ If you would like to ensure that there is data present before subscribing to updates, you can await the result:
260
+
261
+ ```ts
262
+ // this waits for the first value to arrive
263
+ const users = await client.liveQuery.users({
264
+ id: true,
265
+ name: true,
266
+ });
267
+
268
+ // this will guaranteed to have a value set
269
+ users.subscribe((s) => s?.at(0));
270
+
271
+ // you can directly access the values of an awaited result
272
+ console.log(users.firstName)
273
+ ```
package/index.cjs CHANGED
@@ -1,9 +1,105 @@
1
- 'use strict';var graphqlArmor=require('@escape.tech/graphql-armor'),pluginDisableIntrospection=require('@graphql-yoga/plugin-disable-introspection'),esToolkit=require('es-toolkit'),graphqlYoga=require('graphql-yoga'),sofaApi=require('sofa-api'),drizzleOrm=require('drizzle-orm'),casing=require('drizzle-orm/casing'),pgCore=require('drizzle-orm/pg-core'),pluralize=require('pluralize'),mysqlCore=require('drizzle-orm/mysql-core'),sqliteCore=require('drizzle-orm/sqlite-core'),et=require('@pothos/core'),st=require('@pothos/plugin-drizzle'),at=require('@pothos/plugin-smart-subscriptions'),graphqlScalars=require('graphql-scalars');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var et__default=/*#__PURE__*/_interopDefault(et);var st__default=/*#__PURE__*/_interopDefault(st);var at__default=/*#__PURE__*/_interopDefault(at);function Y(e){return typeof e=="object"&&e!==null}function Z(e,n){throw new Error("Unexpected invariant triggered.")}var Ie=/\r\n|[\n\r]/g;function Q(e,n){let r=0,u=1;for(let i of e.body.matchAll(Ie)){if(typeof i.index=="number"||Z(),i.index>=n)break;r=i.index+i[0].length,u+=1;}return {line:u,column:n+1-r}}function te(e){return $(e.source,Q(e.source,e.start))}function $(e,n){let r=e.locationOffset.column-1,u="".padStart(r)+e.body,i=n.line-1,t=e.locationOffset.line-1,s=n.line+t,m=n.line===1?r:0,a=n.column+m,c=`${e.name}:${s}:${a}
2
- `,l=u.split(/\r\n|[\n\r]/g),b=l[i];if(b.length>120){let o=Math.floor(a/80),C=a%80,y=[];for(let d=0;d<b.length;d+=80)y.push(b.slice(d,d+80));return c+ee([[`${s} |`,y[0]],...y.slice(1,o+1).map(d=>["|",d]),["|","^".padStart(C)],["|",y[o+1]]])}return c+ee([[`${s-1} |`,l[i-1]],[`${s} |`,b],["|","^".padStart(a)],[`${s+1} |`,l[i+1]]])}function ee(e){let n=e.filter(([u,i])=>i!==void 0),r=Math.max(...n.map(([u])=>u.length));return n.map(([u,i])=>u.padStart(r)+(i?" "+i:"")).join(`
3
- `)}function Ne(e){let n=e[0];return n==null||"kind"in n||"length"in n?{nodes:n,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:n}var L=class e extends Error{constructor(n,...r){var u,i,t;let{nodes:s,source:m,positions:a,path:c,originalError:l,extensions:b}=Ne(r);super(n),this.name="GraphQLError",this.path=c??void 0,this.originalError=l??void 0,this.nodes=ne(Array.isArray(s)?s:s?[s]:void 0);let o=ne((u=this.nodes)===null||u===void 0?void 0:u.map(y=>y.loc).filter(y=>y!=null));this.source=m??(o==null||(i=o[0])===null||i===void 0?void 0:i.source),this.positions=a??o?.map(y=>y.start),this.locations=a&&m?a.map(y=>Q(m,y)):o?.map(y=>Q(y.source,y.start));let C=Y(l?.extensions)?l?.extensions:void 0;this.extensions=(t=b??C)!==null&&t!==void 0?t:Object.create(null),Object.defineProperties(this,{message:{writable:true,enumerable:true},name:{enumerable:false},nodes:{enumerable:false},source:{enumerable:false},positions:{enumerable:false},originalError:{enumerable:false}}),l!=null&&l.stack?Object.defineProperty(this,"stack",{value:l.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let n=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(n+=`
1
+ 'use strict';var promises=require('fs/promises'),path=require('path'),esToolkit=require('es-toolkit'),wonka=require('wonka'),graphqlArmor=require('@escape.tech/graphql-armor'),pluginDisableIntrospection=require('@graphql-yoga/plugin-disable-introspection'),graphqlYoga=require('graphql-yoga'),sofaApi=require('sofa-api'),drizzleOrm=require('drizzle-orm'),casing=require('drizzle-orm/casing'),pgCore=require('drizzle-orm/pg-core'),pluralize=require('pluralize'),mysqlCore=require('drizzle-orm/mysql-core'),sqliteCore=require('drizzle-orm/sqlite-core'),kr=require('@pothos/core'),Vr=require('@pothos/plugin-drizzle'),Mr=require('@pothos/plugin-smart-subscriptions'),graphqlScalars=require('graphql-scalars');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var kr__default=/*#__PURE__*/_interopDefault(kr);var Vr__default=/*#__PURE__*/_interopDefault(Vr);var Mr__default=/*#__PURE__*/_interopDefault(Mr);function et({apiUrl:e,rumbleImportPath:t,useExternalUrqlClient:n,availableSubscriptions:r}){let o=[],i="";return typeof n=="string"?o.push(`import { urqlClient } from "${n}";`):(o.push("import { Client, fetchExchange } from '@urql/core';"),o.push("import { cacheExchange } from '@urql/exchange-graphcache';")),o.push(`import { makeLiveQuery, makeMutation, makeSubscription, makeQuery } from '${t}';`),n||(i+=`
2
+ const urqlClient = new Client({
3
+ url: "${e??"PLEASE PROVIDE A URL WHEN GENERATING OR IMPORT AN EXTERNAL URQL CLIENT"}",
4
+ fetchSubscriptions: true,
5
+ exchanges: [cacheExchange({}), fetchExchange],
6
+ fetchOptions: {
7
+ credentials: "include",
8
+ },
9
+ requestPolicy: "cache-and-network",
10
+ });
11
+ `),i+=`
12
+ export const client = {
13
+ /**
14
+ * A query and subscription combination. First queries and if exists, also subscribes to a subscription of the same name.
15
+ * Combines the results of both, so the result is first the query result and then live updates from the subscription.
16
+ * Assumes that the query and subscription return the same fields as per default when using the rumble query helpers.
17
+ * If no subscription with the same name exists, this will just be a query.
18
+ */
19
+ liveQuery: makeLiveQuery<Query>({
20
+ urqlClient,
21
+ availableSubscriptions: new Set([${r.values().toArray().map(s=>`"${s}"`).join(", ")}]),
22
+ }),
23
+ /**
24
+ * A mutation that can be used to e.g. create, update or delete data.
25
+ */
26
+ mutate: makeMutation<Mutation>({
27
+ urqlClient,
28
+ }),
29
+ /**
30
+ * A continuous stream of results that updates when the server sends new data.
31
+ */
32
+ subscribe: makeSubscription<Subscription>({
33
+ urqlClient,
34
+ }),
35
+ /**
36
+ * A one-time fetch of data.
37
+ */
38
+ query: makeQuery<Query>({
39
+ urqlClient,
40
+ }),
41
+ }`,{imports:o,code:i}}function C(e,t){throw new Error(t)}function ce(e){return typeof e=="object"&&e!==null}function tt(e,t){throw new Error("Unexpected invariant triggered.")}var Yt=/\r\n|[\n\r]/g;function re(e,t){let n=0,r=1;for(let o of e.body.matchAll(Yt)){if(typeof o.index=="number"||tt(),o.index>=t)break;n=o.index+o[0].length,r+=1;}return {line:r,column:t+1-n}}function rt(e){return Re(e.source,re(e.source,e.start))}function Re(e,t){let n=e.locationOffset.column-1,r="".padStart(n)+e.body,o=t.line-1,i=e.locationOffset.line-1,s=t.line+i,l=t.line===1?n:0,u=t.column+l,p=`${e.name}:${s}:${u}
42
+ `,a=r.split(/\r\n|[\n\r]/g),m=a[o];if(m.length>120){let c=Math.floor(u/80),x=u%80,h=[];for(let y=0;y<m.length;y+=80)h.push(m.slice(y,y+80));return p+nt([[`${s} |`,h[0]],...h.slice(1,c+1).map(y=>["|",y]),["|","^".padStart(x)],["|",h[c+1]]])}return p+nt([[`${s-1} |`,a[o-1]],[`${s} |`,m],["|","^".padStart(u)],[`${s+1} |`,a[o+1]]])}function nt(e){let t=e.filter(([r,o])=>o!==void 0),n=Math.max(...t.map(([r])=>r.length));return t.map(([r,o])=>r.padStart(n)+(o?" "+o:"")).join(`
43
+ `)}function Ht(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}var L=class e extends Error{constructor(t,...n){var r,o,i;let{nodes:s,source:l,positions:u,path:p,originalError:a,extensions:m}=Ht(n);super(t),this.name="GraphQLError",this.path=p??void 0,this.originalError=a??void 0,this.nodes=it(Array.isArray(s)?s:s?[s]:void 0);let c=it((r=this.nodes)===null||r===void 0?void 0:r.map(h=>h.loc).filter(h=>h!=null));this.source=l??(c==null||(o=c[0])===null||o===void 0?void 0:o.source),this.positions=u??c?.map(h=>h.start),this.locations=u&&l?u.map(h=>re(l,h)):c?.map(h=>re(h.source,h.start));let x=ce(a?.extensions)?a?.extensions:void 0;this.extensions=(i=m??x)!==null&&i!==void 0?i:Object.create(null),Object.defineProperties(this,{message:{writable:true,enumerable:true},name:{enumerable:false},nodes:{enumerable:false},source:{enumerable:false},positions:{enumerable:false},originalError:{enumerable:false}}),a!=null&&a.stack?Object.defineProperty(this,"stack",{value:a.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(t+=`
4
44
 
5
- `+te(r.loc));else if(this.source&&this.locations)for(let r of this.locations)n+=`
45
+ `+rt(n.loc));else if(this.source&&this.locations)for(let n of this.locations)t+=`
6
46
 
7
- `+$(this.source,r);return n}toJSON(){let n={message:this.message};return this.locations!=null&&(n.locations=this.locations),this.path!=null&&(n.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(n.extensions=this.extensions),n}};function ne(e){return e===void 0||e.length===0?void 0:e}var A=class extends Error{constructor(n){super(n),this.name="RumbleError";}},k=class extends L{};var V=e=>{if(!e)throw new k("Value not found but required (findFirst)");return e},Pe=e=>{let n=e.at(0);if(!n)throw new k("Value not found but required (firstEntry)");return n},re=async({filters:e,entities:n,context:r})=>(await Promise.all(e.map(u=>u({context:r,entities:n})))).reduce((u,i)=>(u.push(...i),u),[]);function ve(e){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r===null?void 0:r]))}function z(e){let n,r=false;return ()=>(r||(n=e(),r=true),n)}var G=(e,n)=>new A(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function ie(e){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(e))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(e))return {value1:"a",value2:"b"};if(["uuid"].includes(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(e))return {value1:true,value2:false};if(["timestamp","datetime"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(e))return {value1:{a:1},value2:{b:2}};throw G(e,"Distinct")}var M=Symbol.for("drizzle:Name"),oe=Symbol.for("drizzle:Columns");function P({dbName:e,tsName:n,table:r,db:u}){let i=r;if(n&&(i=u._.relations.schema[n]),e&&(i=Object.values(u._.relations.schema).find(t=>t[M]===e)),!i)throw new A(`Could not find schema for ${JSON.stringify({tsName:n,dbName:e,table:r?.[M]}).toString()}`);return {tableSchema:i,columns:i[oe],get primaryColumns(){return Object.entries(i[oe]).filter(([t,s])=>s.primary).reduce((t,[s,m])=>(t[s]=m,t),{})},relations:u._.relations.config[n],dbName:i[M],get tsName(){return Object.entries(u._.relations.schema).find(([t,s])=>s===i).at(0)}}}function Oe(e){return typeof e!="function"}function Fe(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var se=({db:e,actions:n,defaultLimit:r})=>{let u={},i={},t={},s=m=>{for(let a of n)t[m]||(t[m]={}),t[m][a]||(t[m][a]=[]);return {allow:a=>{let c=i[m];c||(c={},i[m]=c);let l=Array.isArray(a)?a:[a];for(let b of l){let o=c[b];o||(o="unspecified",c[b]=o);}return {when:b=>{for(let o of l)c[o]==="unspecified"&&(c[o]=[]),c[o].push(b);}}},filter:a=>{let c=Array.isArray(a)?a:[a];return {by:l=>{for(let b of c)t[m][b].push(l);}}}}};for(let m of Object.keys(e.query))u[m]=s(m);return {...u,z_registeredQueryFilters:i,z_registeredFilters:t,z_buildWithUserContext:m=>{let a={},c=l=>({filter:(b,o)=>{let C=p=>{let x=z(()=>{if(!(!p?.where&&!o?.inject?.where)){if(o?.inject?.where&&p?.where)return {AND:[p?.where,o?.inject?.where]};if(o?.inject?.where&&!p?.where)return o?.inject?.where;if(!o?.inject?.where&&p?.where)return p?.where;!o?.inject?.where&&p?.where;}}),R=z(()=>{let N=x();if(!N)return;let j=P({tsName:l,db:e});return drizzleOrm.relationsFilterToSQL(j.tableSchema,N)}),q=z(()=>{let N=p?.limit??r;return o?.inject?.limit&&(!N||N>o.inject.limit)&&(N=o.inject.limit),p?.limit&&(!N||p.limit>N)&&(N=p.limit),N??void 0}),w=z(()=>{if(!(!p?.columns&&!o?.inject?.columns))return {...p?.columns,...o?.inject?.columns}}),O={query:{single:{get where(){return x()},columns:w()},many:{get where(){return x()},columns:w(),get limit(){return q()}}},sql:{get where(){return R()},columns:w(),get limit(){return q()}}};return w()||(delete O.sql.columns,delete O.query.many.columns,delete O.query.single.columns),O},y=()=>{let p=P({db:e,tsName:l});if(Object.keys(p.primaryColumns).length===0)throw new A(`No primary key found for entity ${l.toString()}`);let x=Object.values(p.primaryColumns)[0],R=ie(x.getSQLType());return {where:{AND:[{[x.name]:R.value1},{[x.name]:R.value2}]}}},d=i?.[l]?.[b];if(d==="unspecified")return C();d||(d=[y()]);let h=d.filter(Oe),S=d.filter(Fe).map(p=>p(m)),g=S.some(p=>p==="allow"),T=[...h,...S].filter(p=>p!==void 0).filter(p=>p!=="allow");!g&&T.length===0&&(T=[y()]);let v;for(let p of T)p?.limit&&(v===void 0||p.limit>v)&&(v=p.limit);let I;for(let p of [...T,o?.inject])p?.columns&&(I===void 0?I=p.columns:I={...I,...p.columns});let D=g?[]:T.filter(p=>p?.where).map(p=>p.where),f=D.length>0?{OR:D}:void 0;return C({where:f,columns:I,limit:v})},runtimeFilters:b=>t[l][b]});for(let l of Object.keys(e.query))a[l]=c(l);return a}}};var ae=({context:e,abilityBuilder:n})=>async r=>{let u=e?await e(r):{};return {...u,abilities:n.z_buildWithUserContext(u)}};function W(e){return e instanceof pgCore.PgEnumColumn}var le=({db:e,schemaBuilder:n})=>{let r=new Map;return ({tsName:i,enumColumn:t,refName:s})=>{let m,a;if(i){let o=e._.relations.schema[i];m=i.toString();let C=Object.values(e._.relations.schema).filter(y=>typeof y=="object").map(y=>Object.values(y[Symbol.for("drizzle:Columns")])).flat(2).find(y=>y.config?.enum===o);if(!C)throw new A(`Could not find applied enum column for ${i.toString()}.
8
- Please ensure that you use the enum at least once as a column of a table!`);a=C.enumValues;}else if(t){let o=Object.entries(e._.relations.schema).find(([C,y])=>y===t.config.enum);if(!o)throw new A(`Could not find enum in schema for ${t.name}!`);m=o[0],a=t.enumValues;}if(!m||!a)throw new A("Could not determine enum structure!");let c=s??`${esToolkit.capitalize(casing.toCamelCase(m))}Enum`,l=r.get(c);return l||(l=n.enumType(c,{values:a}),r.set(c,l),l)}};var ue={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}},DateTime:{type:"string",format:"date-time"},Date:{type:"string",format:"date"}}}};function _({sqlType:e,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(r="Int"),["real","decimal","double","float"].includes(e)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(e)&&(r="ID"),["boolean"].includes(e)&&(r="Boolean"),["timestamp","datetime"].includes(e)&&(r="DateTime"),["date"].includes(e)&&(r="Date"),["json"].includes(e)&&(r="JSON"),r!==void 0)return r;throw G(e,"SQL to GQL")}function je(e){let n=new Set;for(let u of Object.values(e))typeof u=="object"&&(u instanceof pgCore.PgTable?n.add("postgres"):u instanceof mysqlCore.MySqlTable?n.add("mysql"):u instanceof sqliteCore.SQLiteTable&&n.add("sqlite"));let r=Array.from(n);if(r.length===1)return r[0];throw r.length===0?new Error("No tables found in schema, could not determine dialect"):new Error(`Multiple dialects found in schema: ${r.join(", ")}`)}function pe(e){return je(e._.relations.schema)==="postgres"}async function ce(e){if(!pe(e)){console.info("Database dialect is not compatible with search, skipping search initialization.");return}await e.execute(drizzleOrm.sql`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);}function K({search:e,args:n,tableSchema:r,abilities:u}){if(e?.enabled&&n.search&&n.search.length>0){let i=esToolkit.cloneDeep(n.orderBy);n.orderBy=s=>{let m=drizzleOrm.sql.join(Object.entries(i??{}).map(([b,o])=>{if(o==="asc")return drizzleOrm.sql`${s[b]} ASC`;if(o==="desc")return drizzleOrm.sql`${s[b]} DESC`;throw new Error(`Invalid value ${o} for orderBy`)}),drizzleOrm.sql.raw(", ")),a=u.query.many.columns?Object.entries(r.columns).filter(([b,o])=>u.query.many.columns[b]):Object.entries(r.columns),c=drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(a.map(([b,o])=>drizzleOrm.sql`similarity(${s[b]}::TEXT, ${n.search})`),drizzleOrm.sql.raw(", "))}) DESC`;return i?drizzleOrm.sql.join([m,c],drizzleOrm.sql.raw(", ")):c};let t=esToolkit.cloneDeep(n.where);n.where={AND:[t??{},{RAW:s=>drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(Object.entries(r.columns).map(([m,a])=>drizzleOrm.sql`similarity(${s[m]}::TEXT, ${n.search})`),drizzleOrm.sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var $e=e=>typeof e!="object"?false:!!Object.keys(e).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ye=({db:e,search:n,schemaBuilder:r,makePubSubInstance:u,whereArgImplementer:i,orderArgImplementer:t,enumImplementer:s,abilityBuilder:m})=>({table:a,refName:c,readAction:l="read",adjust:b})=>{let o=P({db:e,tsName:a});Object.keys(o.primaryColumns).length===0&&console.warn(`Could not find primary key for ${a.toString()}. Cannot register subscriptions!`);let C=Object.values(o.primaryColumns)[0],{registerOnInstance:y}=u({table:a});return r.drizzleObject(a,{name:c??esToolkit.capitalize(a.toString()),subscribe:(d,h,S)=>{if(!C)return;let g=h[C.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(h)}. Cannot register subscription!`);return}y({instance:d,action:"updated",primaryKeyValue:g});},applyFilters:m?.z_registeredFilters?.[a]?.[l],fields:d=>{let h=o.columns,S=(D,f,p)=>{let x=_({sqlType:D,fieldName:f});switch(x){case "Int":return d.exposeInt(f,{nullable:p});case "String":return d.exposeString(f,{nullable:p});case "Boolean":return d.exposeBoolean(f,{nullable:p});case "Date":return d.field({type:"Date",resolve:R=>R[f],nullable:p});case "DateTime":return d.field({type:"DateTime",resolve:R=>R[f],nullable:p});case "Float":return d.exposeFloat(f,{nullable:p});case "ID":return d.exposeID(f,{nullable:p});case "JSON":return d.field({type:"JSON",resolve:R=>R[f],nullable:p});default:throw new A(`Unsupported object type ${x} for column ${f}`)}},g=new Map,T=b?.(new Proxy(d,{get:(D,f)=>typeof D[f]!="function"||f==="arg"||f==="builder"||f==="graphqlKind"||f==="kind"||f==="listRef"||f==="table"||f==="typename"||f==="variant"||f.toString().startsWith("boolean")||f.toString().startsWith("float")||f.toString().startsWith("id")||f.toString().startsWith("int")||f.toString().startsWith("string")||f.toString().startsWith("expose")?D[f]:(...p)=>{let x=D[f](...p),R=p.find($e);if(!R)throw new A("Expected config object to be passed to adjust field");return g.set(x,{params:p,creatorFunction:D[f],configObject:R}),x}}))??{},v=Object.entries(h).reduce((D,[f,p])=>{if(T[f]){let{params:x,creatorFunction:R,configObject:q}=g.get(T[f]);return typeof q.nullable!="boolean"&&(q.nullable=!p.notNull),T[f]=R.bind(d)(...x),D}if(W(p)){let x=s({enumColumn:p});D[f]=d.field({type:x,resolve:R=>R[f],nullable:!p.notNull});}else D[f]=S(p.getSQLType(),f,!p.notNull);return D},{}),I=Object.entries(o.relations??{}).reduce((D,[f,p])=>{let x=P({db:e,table:p.targetTable}),R=i({dbName:x.dbName}),q=t({dbName:x.dbName}),w=u({table:x.tsName}),O=false,N=true,j="many";p instanceof drizzleOrm.One&&(N=false,O=p.optional,j="single");let H=(E,U)=>{w.registerOnInstance({instance:E,action:"created"}),w.registerOnInstance({instance:E,action:"removed"});};if(T[f]){let{params:E,creatorFunction:U,configObject:F}=g.get(T[f]);return typeof F.nullable!="boolean"&&(F.nullable=O),typeof F.subscribe!="function"&&(F.subscribe=H),T[f]=U.bind(d)(...E),D}let X={where:d.arg({type:R,required:false}),orderBy:d.arg({type:q,required:false}),...N?{offset:d.arg.int({required:false}),limit:d.arg.int({required:false})}:{},search:d.arg.string({required:false})};return (!n?.enabled||!N)&&delete X.search,D[f]=d.relation(f,{args:X,subscribe:H,nullable:O,description:`Get the ${pluralize.plural(x.tsName)} related to this ${pluralize.singular(o.tsName)}`,query:(E,U)=>{E=JSON.parse(JSON.stringify(E)),N&&K({search:n,args:E,tableSchema:x,abilities:U.abilities[x.tsName].filter(l)});let F=U.abilities[x.tsName].filter(l,{inject:{where:E.where,limit:E.limit}}).query[j];return E.offset&&(F.offset=E.offset),E.orderBy&&(F.orderBy=E.orderBy),F}}),D},{});return {...v,...I,...T}}})};var Je=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}OrderInputArgument`,de=({db:e,schemaBuilder:n})=>{let r=new Map,u=z(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??Je(a.tsName),l=r.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=Object.entries(a.columns).reduce((d,[h,S])=>(d[h]=o.field({type:u(),required:false}),d),{}),y=Object.entries(a.relations??{}).reduce((d,[h,S])=>{let g=P({db:e,table:S.targetTable}),T=i({dbName:g.dbName});return d[h]=o.field({type:T,required:false}),d},{});return {...C,...y}}}),r.set(c,l),l)};return i};var He="RUMBLE_SUBSCRIPTION_NOTIFICATION",Xe="REMOVED",Ye="UPDATED",Ze="CREATED",be=({subscriptions:e,db:n})=>{let r=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function t({action:s,tableName:m,primaryKeyValue:a}){let c;switch(s){case "created":c=Ze;break;case "removed":c=Xe;break;case "updated":c=Ye;break;default:throw new Error(`Unknown action: ${s}`)}return `${He}/${m}${a?`/${a}`:""}/${c}`}return {registerOnInstance({instance:s,action:m,primaryKeyValue:a}){let c=t({tableName:i.toString(),action:m,primaryKeyValue:a});s.register(c);},created(){let s=t({tableName:i.toString(),action:"created"});return r.publish(s)},removed(s){let m=t({tableName:i.toString(),action:"removed"});return r.publish(m)},updated(s){let a=(Array.isArray(s)?s:[s]).map(l=>t({tableName:i.toString(),action:"updated",primaryKeyValue:l})),c=Array.from(new Set(a));for(let l of c)r.publish(l);}}}}};var Te=({db:e,schemaBuilder:n,search:r,whereArgImplementer:u,orderArgImplementer:i,makePubSubInstance:t})=>({table:s,readAction:m="read",listAction:a="read"})=>{let c=u({table:s}),l=i({table:s}),b=P({db:e,tsName:s}),o=Object.values(b.primaryColumns)[0],{registerOnInstance:C}=t({table:s});return n.queryFields(y=>{let d={where:y.arg({type:c,required:false}),orderBy:y.arg({type:l,required:false}),limit:y.arg.int({required:false}),offset:y.arg.int({required:false}),search:y.arg.string({required:false})};return r?.enabled||delete d.search,{[pluralize.plural(s.toString())]:y.drizzleField({type:[s],nullable:false,smartSubscription:true,description:`List all ${pluralize.plural(s.toString())}`,subscribe:(h,S,g,T,v)=>{C({instance:h,action:"created"}),C({instance:h,action:"removed"});},args:d,resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g)),K({search:r,args:g,tableSchema:b,abilities:T.abilities[s].filter(a)});let I=T.abilities[s].filter(a,g.where||g.limit||g.offset?{inject:{where:g.where,limit:g.limit}}:void 0).query.many;g.offset&&(I.offset=g.offset),g.orderBy&&(I.orderBy=g.orderBy);let D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findMany(D)}}),[pluralize.singular(s.toString())]:y.drizzleField({type:s,nullable:false,smartSubscription:true,description:`Get a single ${pluralize.singular(s.toString())} by ID`,args:{id:y.arg.id({required:true})},resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g));let I=T.abilities[s].filter(m,{inject:{where:{[o.name]:g.id}}}).query.single,D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findFirst(D).then(V)}})}})};var De="ManualFiltersPlugin",Ce=De,xe="applyFilters",J=class extends et.BasePlugin{wrapResolve(n,r){return async(u,i,t,s)=>{let m,a=r?.type;if(a.kind==="List"?m=a.type?.ref.currentConfig.pothosOptions[xe]:a.kind==="Object"&&(m=a.ref.currentConfig.pothosOptions[xe]),!m||!Array.isArray(m)||m.length===0)return n(u,i,t,s);let c=await n(u,i,t,s),l=Array.isArray(c)?c:[c],b=Array.isArray(m)?m:[m],o=await re({filters:b,entities:l,context:t});return Array.isArray(c)?o:o[0]??null}}};et__default.default.registerPlugin(De,J);var it=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}WhereInputArgument`,Se=({db:e,schemaBuilder:n,enumImplementer:r})=>{let u=new Map,i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??it(a.tsName),l=u.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=(h,S)=>{let g=_({sqlType:h,fieldName:S});switch(g){case "Int":return o.field({type:"IntWhereInputArgument"});case "String":return o.field({type:"StringWhereInputArgument"});case "Boolean":return o.boolean({required:false});case "Date":return o.field({type:"DateWhereInputArgument"});case "DateTime":return o.field({type:"DateWhereInputArgument"});case "Float":return o.field({type:"FloatWhereInputArgument"});case "ID":return o.id({required:false});case "JSON":return o.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${g} for column ${h}`)}},y=Object.entries(a.columns).reduce((h,[S,g])=>{if(W(g)){let T=r({enumColumn:g});h[S]=o.field({type:T,required:false});}else h[S]=C(g.getSQLType(),S);return h},{}),d=Object.entries(a.relations??{}).reduce((h,[S,g])=>{let T=P({db:e,table:g.targetTable}),v=i({dbName:T.dbName});return h[S]=o.field({type:v,required:false}),h},{});return {...y,...d}}}),u.set(c,l),l)};return i};function Re(e){let n=e.inputRef("IntWhereInputArgument").implement({fields:t=>({eq:t.int(),ne:t.int(),gt:t.int(),gte:t.int(),lt:t.int(),lte:t.int(),in:t.intList(),notIn:t.intList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.intList(),arrayContained:t.intList(),arrayContains:t.intList(),AND:t.field({type:[n]}),OR:t.field({type:[n]}),NOT:t.field({type:n})})}),r=e.inputRef("FloatWhereInputArgument").implement({fields:t=>({eq:t.float(),ne:t.float(),gt:t.float(),gte:t.float(),lt:t.float(),lte:t.float(),in:t.floatList(),notIn:t.floatList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.floatList(),arrayContained:t.floatList(),arrayContains:t.floatList(),AND:t.field({type:[r]}),OR:t.field({type:[r]}),NOT:t.field({type:r})})}),u=e.inputRef("StringWhereInputArgument").implement({fields:t=>({eq:t.string(),ne:t.string(),gt:t.string(),gte:t.string(),lt:t.string(),lte:t.string(),in:t.stringList(),notIn:t.stringList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.stringList(),arrayContained:t.stringList(),arrayContains:t.stringList(),AND:t.field({type:[u]}),OR:t.field({type:[u]}),NOT:t.field({type:u})})}),i=e.inputRef("DateWhereInputArgument").implement({fields:t=>({eq:t.field({type:"Date"}),ne:t.field({type:"Date"}),gt:t.field({type:"Date"}),gte:t.field({type:"Date"}),lt:t.field({type:"Date"}),lte:t.field({type:"Date"}),in:t.field({type:["Date"]}),notIn:t.field({type:["Date"]}),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.field({type:["Date"]}),arrayContained:t.field({type:["Date"]}),arrayContains:t.field({type:["Date"]}),AND:t.field({type:[i]}),OR:t.field({type:[i]}),NOT:t.field({type:i})})});}var Ae=({db:e,disableDefaultObjects:n,pubsub:r,pothosConfig:u})=>{let i=new et__default.default({...u,plugins:[Ce,st__default.default,at__default.default,...u?.plugins??[]],drizzle:{client:e,relations:e._.relations,getTableConfig(t){return {columns:Object.values(t[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(t[Symbol.for("drizzle:Columns")]).filter(s=>s.primary)}}},smartSubscriptions:{...at.subscribeOptionsFromIterator((t,s)=>r.subscribe(t))}});return i.addScalarType("JSON",graphqlScalars.JSONResolver),i.addScalarType("Date",graphqlScalars.DateResolver),i.addScalarType("DateTime",graphqlScalars.DateTimeISOResolver),Re(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var gt=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&ce(e.db);let n=se(e),r=ae({...e,abilityBuilder:n}),{makePubSubInstance:u,pubsub:i}=be({...e}),{schemaBuilder:t}=Ae({...e,pubsub:i}),s=le({...e,schemaBuilder:t}),m=Se({...e,schemaBuilder:t,enumImplementer:s}),a=de({...e,schemaBuilder:t}),c=ye({...e,schemaBuilder:t,makePubSubInstance:u,whereArgImplementer:m,orderArgImplementer:a,enumImplementer:s,abilityBuilder:n}),l=Te({...e,schemaBuilder:t,whereArgImplementer:m,orderArgImplementer:a,makePubSubInstance:u}),b=z(()=>t.toSchema());return {abilityBuilder:n,schemaBuilder:t,createYoga:y=>{let d=y?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return graphqlYoga.createYoga({...y,graphiql:d,plugins:[...y?.plugins??[],...d?[]:[pluginDisableIntrospection.useDisableIntrospection(),graphqlArmor.EnvelopArmorPlugin()]].filter(Boolean),schema:b(),context:r})},createSofa:y=>(y.openAPI&&esToolkit.merge(y.openAPI,ue),sofaApi.useSofa({...y,schema:b(),context:r})),object:c,whereArg:m,orderArg:a,query:l,pubsub:u,enum_:s}};exports.RumbleError=A;exports.RumbleErrorSafe=k;exports.assertFindFirstExists=V;exports.assertFirstEntryExists=Pe;exports.mapNullFieldsToUndefined=ve;exports.rumble=gt;//# sourceMappingURL=index.cjs.map
47
+ `+Re(this.source,n);return t}toJSON(){let t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}};function it(e){return e===void 0||e.length===0?void 0:e}var ve={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},Xt=new Set(Object.keys(ve));function Oe(e){let t=e?.kind;return typeof t=="string"&&Xt.has(t)}var ot;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription";})(ot||(ot={}));var B;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension";})(B||(B={}));function Le(e){return e===9||e===32}function Zt(e){return e>=48&&e<=57}function st(e){return e>=97&&e<=122||e>=65&&e<=90}function at(e){return st(e)||e===95}function lt(e){return st(e)||Zt(e)||e===95}function ut(e,t){let n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),o=r.length===1,i=r.length>1&&r.slice(1).every(x=>x.length===0||Le(x.charCodeAt(0))),s=n.endsWith('\\"""'),l=e.endsWith('"')&&!s,u=e.endsWith("\\"),p=l||u,a=(!o||e.length>70||p||i||s),m="",c=o&&Le(e.charCodeAt(0));return (a&&!c||i)&&(m+=`
48
+ `),m+=n,(a||p)&&(m+=`
49
+ `),'"""'+m+'"""'}function P(e){return me(e,[])}function me(e,t){switch(typeof e){case "string":return JSON.stringify(e);case "function":return e.name?`[function ${e.name}]`:"[function]";case "object":return en(e,t);default:return String(e)}}function en(e,t){if(e===null)return "null";if(t.includes(e))return "[Circular]";let n=[...t,e];if(tn(e)){let r=e.toJSON();if(r!==e)return typeof r=="string"?r:me(r,n)}else if(Array.isArray(e))return rn(e,n);return nn(e,n)}function tn(e){return typeof e.toJSON=="function"}function nn(e,t){let n=Object.entries(e);return n.length===0?"{}":t.length>2?"["+on(e)+"]":"{ "+n.map(([o,i])=>o+": "+me(i,t)).join(", ")+" }"}function rn(e,t){if(e.length===0)return "[]";if(t.length>2)return "[Array]";let n=Math.min(10,e.length),r=e.length-n,o=[];for(let i=0;i<n;++i)o.push(me(e[i],t));return r===1?o.push("... 1 more item"):r>1&&o.push(`... ${r} more items`),"["+o.join(", ")+"]"}function on(e){let t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){let n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}var sn=globalThis.process&&process.env.NODE_ENV==="production",z=sn?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return true;if(typeof t=="object"&&t!==null){var r;let o=n.prototype[Symbol.toStringTag],i=Symbol.toStringTag in t?t[Symbol.toStringTag]:(r=t.constructor)===null||r===void 0?void 0:r.name;if(o===i){let s=P(t);throw new Error(`Cannot use ${o} "${s}" from another module or realm.
50
+
51
+ Ensure that there is only one instance of "graphql" in the node_modules
52
+ directory. If different versions of "graphql" are the dependencies of other
53
+ relied on modules, use "resolutions" to ensure only one version is installed.
54
+
55
+ https://yarnpkg.com/en/docs/selective-version-resolutions
56
+
57
+ Duplicate "graphql" modules cannot be used at the same time since different
58
+ versions may have different capabilities and behavior. The data from one
59
+ version used in the function from another could produce confusing and
60
+ spurious results.`)}}return false};function pt(e,t){let[n,r]=t?[e,t]:[void 0,e],o=" Did you mean ";n&&(o+=n+" ");let i=r.map(u=>`"${u}"`);switch(i.length){case 0:return "";case 1:return o+i[0]+"?";case 2:return o+i[0]+" or "+i[1]+"?"}let s=i.slice(0,5),l=s.pop();return o+s.join(", ")+", or "+l+"?"}function Be(e){return e}function ct(e,t){let n=Object.create(null);for(let r of e)n[t(r)]=r;return n}function ie(e,t,n){let r=Object.create(null);for(let o of e)r[t(o)]=n(o);return r}function oe(e,t){let n=Object.create(null);for(let r of Object.keys(e))n[r]=t(e[r],r);return n}function mt(e,t){let n=0,r=0;for(;n<e.length&&r<t.length;){let o=e.charCodeAt(n),i=t.charCodeAt(r);if(fe(o)&&fe(i)){let s=0;do++n,s=s*10+o-we,o=e.charCodeAt(n);while(fe(o)&&s>0);let l=0;do++r,l=l*10+i-we,i=t.charCodeAt(r);while(fe(i)&&l>0);if(s<l)return -1;if(s>l)return 1}else {if(o<i)return -1;if(o>i)return 1;++n,++r;}}return e.length-t.length}var we=48,an=57;function fe(e){return !isNaN(e)&&we<=e&&e<=an}function dt(e,t){let n=Object.create(null),r=new Pe(e),o=Math.floor(e.length*.4)+1;for(let i of t){let s=r.measure(i,o);s!==void 0&&(n[i]=s);}return Object.keys(n).sort((i,s)=>{let l=n[i]-n[s];return l!==0?l:mt(i,s)})}var Pe=class{constructor(t){this._input=t,this._inputLowerCase=t.toLowerCase(),this._inputArray=ft(this._inputLowerCase),this._rows=[new Array(t.length+1).fill(0),new Array(t.length+1).fill(0),new Array(t.length+1).fill(0)];}measure(t,n){if(this._input===t)return 0;let r=t.toLowerCase();if(this._inputLowerCase===r)return 1;let o=ft(r),i=this._inputArray;if(o.length<i.length){let a=o;o=i,i=a;}let s=o.length,l=i.length;if(s-l>n)return;let u=this._rows;for(let a=0;a<=l;a++)u[0][a]=a;for(let a=1;a<=s;a++){let m=u[(a-1)%3],c=u[a%3],x=c[0]=a;for(let h=1;h<=l;h++){let y=o[a-1]===i[h-1]?0:1,T=Math.min(m[h]+1,c[h-1]+1,m[h-1]+y);if(a>1&&h>1&&o[a-1]===i[h-2]&&o[a-2]===i[h-1]){let N=u[(a-2)%3][h-2];T=Math.min(T,N+1);}T<x&&(x=T),c[h]=T;}if(x>n)return}let p=u[s%3][l];return p<=n?p:void 0}};function ft(e){let t=e.length,n=new Array(t);for(let r=0;r<t;++r)n[r]=e.charCodeAt(r);return n}function k(e){if(e==null)return Object.create(null);if(Object.getPrototypeOf(e)===null)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=r;return t}function yt(e){return `"${e.replace(ln,un)}"`}var ln=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function un(e){return pn[e.charCodeAt(0)]}var pn=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"];var cn=Object.freeze({});function ht(e,t,n=ve){let r=new Map;for(let N of Object.values(B))r.set(N,mn(t,N));let o,i=Array.isArray(e),s=[e],l=-1,u=[],p=e,a,m,c=[],x=[];do{l++;let N=l===s.length,g=N&&u.length!==0;if(N){if(a=x.length===0?void 0:c[c.length-1],p=m,m=x.pop(),g)if(i){p=p.slice();let R=0;for(let[I,E]of u){let b=I-R;E===null?(p.splice(b,1),R++):p[b]=E;}}else {p={...p};for(let[R,I]of u)p[R]=I;}l=o.index,s=o.keys,u=o.edits,i=o.inArray,o=o.prev;}else if(m){if(a=i?l:s[l],p=m[a],p==null)continue;c.push(a);}let D;if(!Array.isArray(p)){var h,y;Oe(p)||C(false,`Invalid AST Node: ${P(p)}.`);let R=N?(h=r.get(p.kind))===null||h===void 0?void 0:h.leave:(y=r.get(p.kind))===null||y===void 0?void 0:y.enter;if(D=R?.call(t,p,a,m,c,x),D===cn)break;if(D===false){if(!N){c.pop();continue}}else if(D!==void 0&&(u.push([a,D]),!N))if(Oe(D))p=D;else {c.pop();continue}}if(D===void 0&&g&&u.push([a,p]),N)c.pop();else {var T;o={inArray:i,index:l,keys:s,edits:u,prev:o},i=Array.isArray(p),s=i?p:(T=n[p.kind])!==null&&T!==void 0?T:[],l=-1,u=[],m&&x.push(m),m=p;}}while(o!==void 0);return u.length!==0?u[u.length-1][1]:e}function mn(e,t){let n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function Fe(e){return ht(e,dn)}var fn=80,dn={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>f(e.definitions,`
61
+
62
+ `)},OperationDefinition:{leave(e){let t=S("(",f(e.variableDefinitions,", "),")"),n=f([e.operation,f([e.name,t]),f(e.directives," ")]," ");return (n==="query"?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r})=>e+": "+t+S(" = ",n)+S(" ",f(r," "))},SelectionSet:{leave:({selections:e})=>q(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:o}){let i=S("",e,": ")+t,s=i+S("(",f(n,", "),")");return s.length>fn&&(s=i+S(`(
63
+ `,de(f(n,`
64
+ `)),`
65
+ )`)),f([s,f(r," "),o]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+S(" ",f(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>f(["...",S("on ",e),f(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:o})=>`fragment ${e}${S("(",f(n,", "),")")} on ${t} ${S("",f(r," ")," ")}`+o},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?ut(e):yt(e)},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+f(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+f(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+S("(",f(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>S("",e,`
66
+ `)+f(["schema",f(t," "),q(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>S("",e,`
67
+ `)+f(["scalar",t,f(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:o})=>S("",e,`
68
+ `)+f(["type",t,S("implements ",f(n," & ")),f(r," "),q(o)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:o})=>S("",e,`
69
+ `)+t+(bt(n)?S(`(
70
+ `,de(f(n,`
71
+ `)),`
72
+ )`):S("(",f(n,", "),")"))+": "+r+S(" ",f(o," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:o})=>S("",e,`
73
+ `)+f([t+": "+n,S("= ",r),f(o," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:o})=>S("",e,`
74
+ `)+f(["interface",t,S("implements ",f(n," & ")),f(r," "),q(o)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>S("",e,`
75
+ `)+f(["union",t,f(n," "),S("= ",f(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>S("",e,`
76
+ `)+f(["enum",t,f(n," "),q(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>S("",e,`
77
+ `)+f([t,f(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>S("",e,`
78
+ `)+f(["input",t,f(n," "),q(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:o})=>S("",e,`
79
+ `)+"directive @"+t+(bt(n)?S(`(
80
+ `,de(f(n,`
81
+ `)),`
82
+ )`):S("(",f(n,", "),")"))+(r?" repeatable":"")+" on "+f(o," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>f(["extend schema",f(e," "),q(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>f(["extend scalar",e,f(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>f(["extend type",e,S("implements ",f(t," & ")),f(n," "),q(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>f(["extend interface",e,S("implements ",f(t," & ")),f(n," "),q(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>f(["extend union",e,f(t," "),S("= ",f(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>f(["extend enum",e,f(t," "),q(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>f(["extend input",e,f(t," "),q(n)]," ")}};function f(e,t=""){var n;return (n=e?.filter(r=>r).join(t))!==null&&n!==void 0?n:""}function q(e){return S(`{
83
+ `,de(f(e,`
84
+ `)),`
85
+ }`)}function S(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function de(e){return S(" ",e.replace(/\n/g,`
86
+ `))}function bt(e){var t;return (t=e?.some(n=>n.includes(`
87
+ `)))!==null&&t!==void 0?t:false}function ye(e,t){switch(e.kind){case B.NULL:return null;case B.INT:return parseInt(e.value,10);case B.FLOAT:return parseFloat(e.value);case B.STRING:case B.ENUM:case B.BOOLEAN:return e.value;case B.LIST:return e.values.map(n=>ye(n,t));case B.OBJECT:return ie(e.fields,n=>n.name.value,n=>ye(n.value,t));case B.VARIABLE:return t?.[e.name.value]}}function Q(e){if(e!=null||C(false,"Must provide name."),typeof e=="string"||C(false,"Expected name to be a string."),e.length===0)throw new L("Expected name to be a non-empty string.");for(let t=1;t<e.length;++t)if(!lt(e.charCodeAt(t)))throw new L(`Names must only contain [_a-zA-Z0-9] but "${e}" does not.`);if(!at(e.charCodeAt(0)))throw new L(`Names must start with [_a-zA-Z] but "${e}" does not.`);return e}function je(e){if(e==="true"||e==="false"||e==="null")throw new L(`Enum values cannot be named: ${e}`);return Q(e)}function be(e){return _e(e)||Qe(e)||ke(e)||qe(e)||ze(e)||Ue(e)||Ge(e)||ge(e)}function _e(e){return z(e,W)}function Qe(e){return z(e,J)}function ke(e){return z(e,se)}function qe(e){return z(e,ae)}function ze(e){return z(e,X)}function Ue(e){return z(e,K)}function Ge(e){return z(e,M)}function ge(e){return z(e,U)}var M=class{constructor(t){be(t)||C(false,`Expected ${P(t)} to be a GraphQL type.`),this.ofType=t;}get[Symbol.toStringTag](){return "GraphQLList"}toString(){return "["+String(this.ofType)+"]"}toJSON(){return this.toString()}},U=class{constructor(t){$e(t)||C(false,`Expected ${P(t)} to be a GraphQL nullable type.`),this.ofType=t;}get[Symbol.toStringTag](){return "GraphQLNonNull"}toString(){return String(this.ofType)+"!"}toJSON(){return this.toString()}};function $e(e){return be(e)&&!ge(e)}function Te(e){return typeof e=="function"?e():e}function xe(e){return typeof e=="function"?e():e}var W=class{constructor(t){var n,r,o,i;let s=(n=t.parseValue)!==null&&n!==void 0?n:Be;this.name=Q(t.name),this.description=t.description,this.specifiedByURL=t.specifiedByURL,this.serialize=(r=t.serialize)!==null&&r!==void 0?r:Be,this.parseValue=s,this.parseLiteral=(o=t.parseLiteral)!==null&&o!==void 0?o:(l,u)=>s(ye(l,u)),this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(i=t.extensionASTNodes)!==null&&i!==void 0?i:[],t.specifiedByURL==null||typeof t.specifiedByURL=="string"||C(false,`${this.name} must provide "specifiedByURL" as a string, but got: ${P(t.specifiedByURL)}.`),t.serialize==null||typeof t.serialize=="function"||C(false,`${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`),t.parseLiteral&&(typeof t.parseValue=="function"&&typeof t.parseLiteral=="function"||C(false,`${this.name} must provide both "parseValue" and "parseLiteral" functions.`));}get[Symbol.toStringTag](){return "GraphQLScalarType"}toConfig(){return {name:this.name,description:this.description,specifiedByURL:this.specifiedByURL,serialize:this.serialize,parseValue:this.parseValue,parseLiteral:this.parseLiteral,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},J=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.isTypeOf=t.isTypeOf,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._fields=()=>xt(t),this._interfaces=()=>Tt(t),t.isTypeOf==null||typeof t.isTypeOf=="function"||C(false,`${this.name} must provide "isTypeOf" as a function, but got: ${P(t.isTypeOf)}.`);}get[Symbol.toStringTag](){return "GraphQLObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return {name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:St(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function Tt(e){var t;let n=Te((t=e.interfaces)!==null&&t!==void 0?t:[]);return Array.isArray(n)||C(false,`${e.name} interfaces must be an Array or a function which returns an Array.`),n}function xt(e){let t=xe(e.fields);return Z(t)||C(false,`${e.name} fields must be an object with field names as keys or a function which returns such an object.`),oe(t,(n,r)=>{var o;Z(n)||C(false,`${e.name}.${r} field config must be an object.`),n.resolve==null||typeof n.resolve=="function"||C(false,`${e.name}.${r} field resolver must be a function if provided, but got: ${P(n.resolve)}.`);let i=(o=n.args)!==null&&o!==void 0?o:{};return Z(i)||C(false,`${e.name}.${r} args must be an object with argument names as keys.`),{name:Q(r),description:n.description,type:n.type,args:yn(i),resolve:n.resolve,subscribe:n.subscribe,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}})}function yn(e){return Object.entries(e).map(([t,n])=>({name:Q(t),description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}))}function Z(e){return ce(e)&&!Array.isArray(e)}function St(e){return oe(e,t=>({description:t.description,type:t.type,args:hn(t.args),resolve:t.resolve,subscribe:t.subscribe,deprecationReason:t.deprecationReason,extensions:t.extensions,astNode:t.astNode}))}function hn(e){return ie(e,t=>t.name,t=>({description:t.description,type:t.type,defaultValue:t.defaultValue,deprecationReason:t.deprecationReason,extensions:t.extensions,astNode:t.astNode}))}var se=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.resolveType=t.resolveType,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._fields=xt.bind(void 0,t),this._interfaces=Tt.bind(void 0,t),t.resolveType==null||typeof t.resolveType=="function"||C(false,`${this.name} must provide "resolveType" as a function, but got: ${P(t.resolveType)}.`);}get[Symbol.toStringTag](){return "GraphQLInterfaceType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return {name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:St(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},ae=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.resolveType=t.resolveType,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._types=bn.bind(void 0,t),t.resolveType==null||typeof t.resolveType=="function"||C(false,`${this.name} must provide "resolveType" as a function, but got: ${P(t.resolveType)}.`);}get[Symbol.toStringTag](){return "GraphQLUnionType"}getTypes(){return typeof this._types=="function"&&(this._types=this._types()),this._types}toConfig(){return {name:this.name,description:this.description,types:this.getTypes(),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function bn(e){let t=Te(e.types);return Array.isArray(t)||C(false,`Must provide Array of types or a function which returns such an array for Union ${e.name}.`),t}var X=class{constructor(t){var n;this.name=Q(t.name),this.description=t.description,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this._values=typeof t.values=="function"?t.values:gt(this.name,t.values),this._valueLookup=null,this._nameLookup=null;}get[Symbol.toStringTag](){return "GraphQLEnumType"}getValues(){return typeof this._values=="function"&&(this._values=gt(this.name,this._values())),this._values}getValue(t){return this._nameLookup===null&&(this._nameLookup=ct(this.getValues(),n=>n.name)),this._nameLookup[t]}serialize(t){this._valueLookup===null&&(this._valueLookup=new Map(this.getValues().map(r=>[r.value,r])));let n=this._valueLookup.get(t);if(n===void 0)throw new L(`Enum "${this.name}" cannot represent value: ${P(t)}`);return n.name}parseValue(t){if(typeof t!="string"){let r=P(t);throw new L(`Enum "${this.name}" cannot represent non-string value: ${r}.`+he(this,r))}let n=this.getValue(t);if(n==null)throw new L(`Value "${t}" does not exist in "${this.name}" enum.`+he(this,t));return n.value}parseLiteral(t,n){if(t.kind!==B.ENUM){let o=Fe(t);throw new L(`Enum "${this.name}" cannot represent non-enum value: ${o}.`+he(this,o),{nodes:t})}let r=this.getValue(t.value);if(r==null){let o=Fe(t);throw new L(`Value "${o}" does not exist in "${this.name}" enum.`+he(this,o),{nodes:t})}return r.value}toConfig(){let t=ie(this.getValues(),n=>n.name,n=>({description:n.description,value:n.value,deprecationReason:n.deprecationReason,extensions:n.extensions,astNode:n.astNode}));return {name:this.name,description:this.description,values:t,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function he(e,t){let n=e.getValues().map(o=>o.name),r=dt(t,n);return pt("the enum value",r)}function gt(e,t){return Z(t)||C(false,`${e} values must be an object with value names as keys.`),Object.entries(t).map(([n,r])=>(Z(r)||C(false,`${e}.${n} must refer to an object with a "value" key representing an internal value but got: ${P(r)}.`),{name:je(n),description:r.description,value:r.value!==void 0?r.value:n,deprecationReason:r.deprecationReason,extensions:k(r.extensions),astNode:r.astNode}))}var K=class{constructor(t){var n,r;this.name=Q(t.name),this.description=t.description,this.extensions=k(t.extensions),this.astNode=t.astNode,this.extensionASTNodes=(n=t.extensionASTNodes)!==null&&n!==void 0?n:[],this.isOneOf=(r=t.isOneOf)!==null&&r!==void 0?r:false,this._fields=gn.bind(void 0,t);}get[Symbol.toStringTag](){return "GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let t=oe(this.getFields(),n=>({description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:n.extensions,astNode:n.astNode}));return {name:this.name,description:this.description,fields:t,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes,isOneOf:this.isOneOf}}toString(){return this.name}toJSON(){return this.toString()}};function gn(e){let t=xe(e.fields);return Z(t)||C(false,`${e.name} fields must be an object with field names as keys or a function which returns such an object.`),oe(t,(n,r)=>(!("resolve"in n)||C(false,`${e.name}.${r} field has a resolve property, but Input Types cannot define resolvers.`),{name:Q(r),description:n.description,type:n.type,defaultValue:n.defaultValue,deprecationReason:n.deprecationReason,extensions:k(n.extensions),astNode:n.astNode}))}function Ve(e){if(e instanceof J)return Kn(e);if(e instanceof W)return er(e);if(e instanceof X)return tr(e);if(e instanceof K)return Yn(e)}function Kn(e){let t=new Map;for(let[n,r]of Object.entries(e.getFields()))t.set(n,Hn(r.type,r.args));return `{
88
+ ${t.entries().map(([n,r])=>`${n}: ${r}`).toArray().join(`,
89
+ `)}
90
+ }`}function Yn(e){let t=new Map;for(let[n,r]of Object.entries(e.getFields()))t.set(n,Xn(r.type));return `{
91
+ ${t.entries().map(([n,r])=>`${n}${r.includes("| undefined")?"?":""}: ${r}`).toArray().join(`,
92
+ `)}
93
+ }`}function Hn(e,t){let n=false,r=false;for(let l=0;l<3;l++)e instanceof M&&(r=true,e=e.ofType),e instanceof U&&(n=true,e=e.ofType);let o=e.name;r&&(o+="[]"),n||(o+=" | null");let i=e instanceof J,s=new Map;for(let l of t??[])s.set(l.name,Zn(l.type));if(i){let l=s.entries().every(([,p])=>p.includes("| undefined"));return `(${(t??[]).length>0?`p${l?"?":""}: {
94
+ ${s.entries().map(([p,a])=>` ${p}${a.includes("| undefined")?"?":""}: ${a}`).toArray().join(`,
95
+ `)}
96
+ }`:""}) => ${o}`}else return o}function Xn(e){let t=false,n=false;for(let o=0;o<3;o++)e instanceof M&&(n=true,e=e.ofType),e instanceof U&&(t=true,e=e.ofType);let r=e.name;return n&&(r+="[]"),t?n&&(r+=" | undefined"):r+=" | null | undefined",r}function Zn(e){let t="unknown",n=true;return e instanceof U&&(n=false,e=e.ofType),(e instanceof K||e instanceof W)&&(t=e.name),n&&(t+=" | null | undefined"),t}function er(e){switch(e.name){case "ID":return "string";case "String":return "string";case "Boolean":return "boolean";case "Int":return "number";case "Float":return "number";case "Date":return "Date";case "DateTime":return "Date";case "JSON":return "any";default:return "unknown"}}function tr(e){return e.getValues().map(t=>`"${t.name}"`).join(" | ")}async function Me({outputPath:e,schema:t,rumbleImportPath:n="@m1212e/rumble",apiUrl:r,useExternalUrqlClient:o=false}){await promises.exists(e)&&await promises.rm(e,{recursive:true,force:true}),await promises.mkdir(e,{recursive:true}),e.endsWith("/")||(e+="/");let i=[],s="",l=new Map;for(let[p,a]of Object.entries(t.getTypeMap()))p.startsWith("__")||l.set(p,a);for(let[p,a]of l.entries())Ve(a)!==p&&(s+=`
97
+ export type ${p} = ${Ve(a)};
98
+ `);let u=et({apiUrl:r,useExternalUrqlClient:o,rumbleImportPath:n,availableSubscriptions:new Set(Object.keys(t.getSubscriptionType()?.getFields()||{}))});i.push(...u.imports),s+=u.code,await promises.writeFile(path.join(e,"client.ts"),`${i.join(`
99
+ `)}
100
+ ${s}`);}var ee="__args";function De({queryName:e,input:t,client:n,enableSubscription:r=false}){let o=`${esToolkit.capitalize(e)}Query`,i=Ne(t[ee]??{}),s=a=>`${a} ${o} { ${e}${i} { ${ue(t)} }}`,l,u=wonka.pipe(wonka.merge([n.query(s("query"),{}),r?n.subscription(s("subscription"),{}):wonka.empty]),wonka.map(a=>{let m=a.data?.[e];if(!m&&a.error)throw a.error;return m}),wonka.onPush(a=>{l&&Object.assign(l,a);})),p=new Promise(a=>{let m=wonka.toObservable(u).subscribe(c=>{m();let x=wonka.pipe(wonka.merge([u,wonka.fromValue(c)]),wonka.toObservable);l={...c,...x},a(l);}).unsubscribe;});return Object.assign(p,wonka.toObservable(u)),p}function Nt({mutationName:e,input:t,client:n}){let r=`${esToolkit.capitalize(e)}Mutation`,o=Ne(t[ee]??{}),i=wonka.pipe(n.mutation(`mutation ${r} { ${e}${o} { ${ue(t)} }}`,{}),wonka.map(u=>{let p=u.data?.[e];if(!p&&u.error)throw u.error;return p})),s=wonka.toObservable(i),l=wonka.toPromise(i).then(u=>(Object.assign(u,s),u));return Object.assign(l,s),l}function Et({subscriptionName:e,input:t,client:n}){let r=`${esToolkit.capitalize(e)}Subscription`,o=Ne(t[ee]??{});return wonka.pipe(n.subscription(`subscription ${r} { ${e}${o} { ${ue(t)} }}`,{}),wonka.map(i=>{let s=i.data?.[e];if(!s&&i.error)throw i.error;return s}),wonka.toObservable)}function ue(e){return Object.entries(e).filter(([t])=>t!==ee).reduce((t,[n,r])=>{if(typeof r=="object"){if(r[ee]){let o=Ne(r[ee]);return t+=`${n}${o} { ${ue(r)} }
101
+ `,t}t+=`${n} { ${ue(r)} }
102
+ `;}else t+=`${n}
103
+ `;return t},"")}function Ne(e){let t=Object.entries(e);return t.length===0?"":`(${t.map(([n,r])=>`${n}: ${At(r)}`).join(", ")})`}function At(e){switch(typeof e){case "string":return `"${e}"`;case "number":return `${e}`;case "bigint":return `${e}`;case "boolean":return `${e}`;case "symbol":throw new Error("Cannot stringify a symbol to send as gql arg");case "undefined":return "null";case "object":return `{ ${Object.entries(e).map(([t,n])=>`${t}: ${At(n)}`).join(", ")} }`;case "function":throw new Error("Cannot stringify a function to send as gql arg")}}function cr({urqlClient:e,availableSubscriptions:t}){return new Proxy({},{get:(n,r)=>o=>De({queryName:r,input:o,client:e,enableSubscription:t.has(r)})})}function mr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>Nt({mutationName:n,input:r,client:e})})}function fr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>De({queryName:n,input:r,client:e,enableSubscription:false})})}function dr({urqlClient:e}){return new Proxy({},{get:(t,n)=>r=>Et({subscriptionName:n,input:r,client:e})})}var O=class extends Error{constructor(t){super(t),this.name="RumbleError";}},te=class extends L{};var Ke=e=>{if(!e)throw new te("Value not found but required (findFirst)");return e},yr=e=>{let t=e.at(0);if(!t)throw new te("Value not found but required (firstEntry)");return t},Ct=async({filters:e,entities:t,context:n})=>(await Promise.all(e.map(r=>r({context:n,entities:t})))).reduce((r,o)=>(r.push(...o),r),[]);function hr(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n===null?void 0:n]))}function G(e){let t,n=false;return ()=>(n||(t=e(),n=true),t)}var Ee=(e,t)=>new O(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${t})`);function It(e){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(e))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(e))return {value1:"a",value2:"b"};if(["uuid"].includes(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(e))return {value1:true,value2:false};if(["timestamp","datetime"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(e))return {value1:{a:1},value2:{b:2}};throw Ee(e,"Distinct")}var Ye=Symbol.for("drizzle:Name"),Rt=Symbol.for("drizzle:Columns");function _({dbName:e,tsName:t,table:n,db:r}){let o=n;if(t&&(o=r._.relations.schema[t]),e&&(o=Object.values(r._.relations.schema).find(i=>i[Ye]===e)),!o)throw new O(`Could not find schema for ${JSON.stringify({tsName:t,dbName:e,table:n?.[Ye]}).toString()}`);return {tableSchema:o,columns:o[Rt],get primaryColumns(){return Object.entries(o[Rt]).filter(([,i])=>i.primary).reduce((i,[s,l])=>(i[s]=l,i),{})},relations:r._.relations.config[t],dbName:o[Ye],get tsName(){return Object.entries(r._.relations.schema).find(([,i])=>i===o).at(0)}}}function gr(e){return typeof e!="function"}function Tr(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var vt=({db:e,actions:t,defaultLimit:n})=>{let r={},o={},i={},s=l=>{for(let u of t)i[l]||(i[l]={}),i[l][u]||(i[l][u]=[]);return {allow:u=>{let p=o[l];p||(p={},o[l]=p);let a=Array.isArray(u)?u:[u];for(let m of a){let c=p[m];c||(c="unspecified",p[m]=c);}return {when:m=>{for(let c of a)p[c]==="unspecified"&&(p[c]=[]),p[c].push(m);}}},filter:u=>{let p=Array.isArray(u)?u:[u];return {by:a=>{for(let m of p)i[l][m].push(a);}}}}};for(let l of Object.keys(e.query))r[l]=s(l);return {...r,z_registeredQueryFilters:o,z_registeredFilters:i,z_buildWithUserContext:l=>{let u={},p=a=>({filter:(m,c)=>{let x=d=>{let A=G(()=>{if(!(!d?.where&&!c?.inject?.where)){if(c?.inject?.where&&d?.where)return {AND:[d?.where,c?.inject?.where]};if(c?.inject?.where&&!d?.where)return c?.inject?.where;if(!c?.inject?.where&&d?.where)return d?.where;!c?.inject?.where&&d?.where;}}),v=G(()=>{let w=A();if(!w)return;let pe=_({tsName:a,db:e});return drizzleOrm.relationsFilterToSQL(pe.tableSchema,w)}),Y=G(()=>{let w=d?.limit??n;return c?.inject?.limit&&(!w||w>c.inject.limit)&&(w=c.inject.limit),d?.limit&&(!w||d.limit>w)&&(w=d.limit),w??void 0}),H=G(()=>{if(!(!d?.columns&&!c?.inject?.columns))return {...d?.columns,...c?.inject?.columns}}),$={query:{single:{get where(){return A()},columns:H()},many:{get where(){return A()},columns:H(),get limit(){return Y()}}},sql:{get where(){return v()},columns:H(),get limit(){return Y()}}};return H()||(delete $.sql.columns,delete $.query.many.columns,delete $.query.single.columns),$},h=()=>{let d=_({db:e,tsName:a});if(Object.keys(d.primaryColumns).length===0)throw new O(`No primary key found for entity ${a.toString()}`);let A=Object.values(d.primaryColumns)[0],v=It(A.getSQLType());return {where:{AND:[{[A.name]:v.value1},{[A.name]:v.value2}]}}},y=o?.[a]?.[m];if(y==="unspecified")return x();y||(y=[h()]);let T=y.filter(gr),N=y.filter(Tr).map(d=>d(l)),g=N.some(d=>d==="allow"),D=[...T,...N].filter(d=>d!==void 0).filter(d=>d!=="allow");!g&&D.length===0&&(D=[h()]);let R;for(let d of D)d?.limit&&(R===void 0||d.limit>R)&&(R=d.limit);let I;for(let d of [...D,c?.inject])d?.columns&&(I===void 0?I=d.columns:I={...I,...d.columns});let E=g?[]:D.filter(d=>d?.where).map(d=>d.where),b=E.length>0?{OR:E}:void 0;return x({where:b,columns:I,limit:R})},runtimeFilters:m=>i[a][m]});for(let a of Object.keys(e.query))u[a]=p(a);return u}}};var Ot=({builtSchema:e})=>(process.env.NODE_ENV!=="development"&&console.warn("Running rumble client generation in non development mode. Are you sure this is correct?"),async({apiUrl:n,outputPath:r,rumbleImportPath:o,useExternalUrqlClient:i})=>{let s=e();await Me({schema:s,outputPath:r,rumbleImportPath:o,apiUrl:n,useExternalUrqlClient:i});});var Lt=({context:e,abilityBuilder:t})=>async n=>{let r=e?await e(n):{};return {...r,abilities:t.z_buildWithUserContext(r)}};function Ae(e){return e instanceof pgCore.PgEnumColumn}var Bt=({db:e,schemaBuilder:t})=>{let n=new Map;return ({tsName:o,enumColumn:i,refName:s})=>{let l,u;if(o){let c=e._.relations.schema[o];l=o.toString();let x=Object.values(e._.relations.schema).filter(h=>typeof h=="object").map(h=>Object.values(h[Symbol.for("drizzle:Columns")])).flat(2).find(h=>h.config?.enum===c);if(!x)throw new O(`Could not find applied enum column for ${o.toString()}.
104
+ Please ensure that you use the enum at least once as a column of a table!`);u=x.enumValues;}else if(i){let c=Object.entries(e._.relations.schema).find(([,x])=>x===i.config.enum);if(!c)throw new O(`Could not find enum in schema for ${i.name}!`);l=c[0],u=i.enumValues;}if(!l||!u)throw new O("Could not determine enum structure!");let p=s??`${esToolkit.capitalize(casing.toCamelCase(l))}Enum`,a=n.get(p);return a||(a=t.enumType(p,{values:u}),n.set(p,a),a)}};var wt={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{description:"",content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{description:"",content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{description:"",content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}},DateTime:{type:"string",format:"date-time"},Date:{type:"string",format:"date"}}}};function Ce({sqlType:e,fieldName:t}){let n;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(n="Int"),["real","decimal","double","float"].includes(e)&&(n="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(t&&(t.toLowerCase().endsWith("_id")||t.toLowerCase().endsWith("id"))?n="ID":n="String"),["uuid"].includes(e)&&(n="ID"),["boolean"].includes(e)&&(n="Boolean"),["timestamp","datetime"].includes(e)&&(n="DateTime"),["date"].includes(e)&&(n="Date"),["json"].includes(e)&&(n="JSON"),n!==void 0)return n;throw Ee(e,"SQL to GQL")}function Cr(e){let t=new Set;for(let r of Object.values(e))typeof r=="object"&&(r instanceof pgCore.PgTable?t.add("postgres"):r instanceof mysqlCore.MySqlTable?t.add("mysql"):r instanceof sqliteCore.SQLiteTable&&t.add("sqlite"));let n=Array.from(t);if(n.length===1)return n[0];throw n.length===0?new Error("No tables found in schema, could not determine dialect"):new Error(`Multiple dialects found in schema: ${n.join(", ")}`)}function Pt(e){return Cr(e._.relations.schema)==="postgres"}async function jt(e){if(!Pt(e)){console.info("Database dialect is not compatible with search, skipping search initialization.");return}await e.execute(drizzleOrm.sql`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);}function Ie({search:e,args:t,tableSchema:n,abilities:r}){if(e?.enabled&&t.search&&t.search.length>0){let o=esToolkit.cloneDeep(t.orderBy);t.orderBy=s=>{let l=drizzleOrm.sql.join(Object.entries(o??{}).map(([m,c])=>{if(c==="asc")return drizzleOrm.sql`${s[m]} ASC`;if(c==="desc")return drizzleOrm.sql`${s[m]} DESC`;throw new Error(`Invalid value ${c} for orderBy`)}),drizzleOrm.sql.raw(", ")),u=r.query.many.columns?Object.entries(n.columns).filter(([m])=>r.query.many.columns[m]):Object.entries(n.columns),p=drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(u.map(([m])=>drizzleOrm.sql`similarity(${s[m]}::TEXT, ${t.search})`),drizzleOrm.sql.raw(", "))}) DESC`;return o?drizzleOrm.sql.join([l,p],drizzleOrm.sql.raw(", ")):p};let i=esToolkit.cloneDeep(t.where);t.where={AND:[i??{},{RAW:s=>drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(Object.entries(n.columns).map(([l])=>drizzleOrm.sql`similarity(${s[l]}::TEXT, ${t.search})`),drizzleOrm.sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var Lr=e=>typeof e!="object"?false:!!Object.keys(e).some(t=>["args","nullable","query","subscribe","description","type","resolve"].find(n=>n===t)),_t=({db:e,search:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:o,orderArgImplementer:i,enumImplementer:s,abilityBuilder:l})=>({table:u,refName:p,readAction:a="read",adjust:m})=>{let c=_({db:e,tsName:u});Object.keys(c.primaryColumns).length===0&&console.warn(`Could not find primary key for ${u.toString()}. Cannot register subscriptions!`);let x=Object.values(c.primaryColumns)[0],{registerOnInstance:h}=r({table:u});return n.drizzleObject(u,{name:p??esToolkit.capitalize(u.toString()),subscribe:(y,T,N)=>{if(!x)return;let g=T[x.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(T)}. Cannot register subscription!`);return}h({instance:y,action:"updated",primaryKeyValue:g});},applyFilters:l?.z_registeredFilters?.[u]?.[a],fields:y=>{let T=c.columns,N=(E,b,d)=>{let A=Ce({sqlType:E,fieldName:b});switch(A){case "Int":return y.exposeInt(b,{nullable:d});case "String":return y.exposeString(b,{nullable:d});case "Boolean":return y.exposeBoolean(b,{nullable:d});case "Date":return y.field({type:"Date",resolve:v=>v[b],nullable:d});case "DateTime":return y.field({type:"DateTime",resolve:v=>v[b],nullable:d});case "Float":return y.exposeFloat(b,{nullable:d});case "ID":return y.exposeID(b,{nullable:d});case "JSON":return y.field({type:"JSON",resolve:v=>v[b],nullable:d});default:throw new O(`Unsupported object type ${A} for column ${b}`)}},g=new Map,D=m?.(new Proxy(y,{get:(E,b)=>typeof E[b]!="function"||b==="arg"||b==="builder"||b==="graphqlKind"||b==="kind"||b==="listRef"||b==="table"||b==="typename"||b==="variant"||b.toString().startsWith("boolean")||b.toString().startsWith("float")||b.toString().startsWith("id")||b.toString().startsWith("int")||b.toString().startsWith("string")||b.toString().startsWith("expose")?E[b]:(...d)=>{let A=E[b](...d),v=d.find(Lr);if(!v)throw new O("Expected config object to be passed to adjust field");return g.set(A,{params:d,creatorFunction:E[b],configObject:v}),A}}))??{},R=Object.entries(T).reduce((E,[b,d])=>{if(D[b]){let{params:A,creatorFunction:v,configObject:Y}=g.get(D[b]);return typeof Y.nullable!="boolean"&&(Y.nullable=!d.notNull),D[b]=v.bind(y)(...A),E}if(Ae(d)){let A=s({enumColumn:d});E[b]=y.field({type:A,resolve:v=>v[b],nullable:!d.notNull});}else E[b]=N(d.getSQLType(),b,!d.notNull);return E},{}),I=Object.entries(c.relations??{}).reduce((E,[b,d])=>{let A=_({db:e,table:d.targetTable}),v=o({dbName:A.dbName}),Y=i({dbName:A.dbName}),H=r({table:A.tsName}),$=false,w=true,pe="many";d instanceof drizzleOrm.One&&(w=false,$=d.optional,pe="single");let Xe=(j,ne)=>{H.registerOnInstance({instance:j,action:"created"}),H.registerOnInstance({instance:j,action:"removed"});};if(D[b]){let{params:j,creatorFunction:ne,configObject:V}=g.get(D[b]);return typeof V.nullable!="boolean"&&(V.nullable=$),typeof V.subscribe!="function"&&(V.subscribe=Xe),D[b]=ne.bind(y)(...j),E}let Ze={where:y.arg({type:v,required:false}),orderBy:y.arg({type:Y,required:false}),...w?{offset:y.arg.int({required:false}),limit:y.arg.int({required:false})}:{},search:y.arg.string({required:false})};return (!t?.enabled||!w)&&delete Ze.search,E[b]=y.relation(b,{args:Ze,subscribe:Xe,nullable:$,description:`Get the ${pluralize.plural(A.tsName)} related to this ${pluralize.singular(c.tsName)}`,query:(j,ne)=>{j=JSON.parse(JSON.stringify(j)),w&&Ie({search:t,args:j,tableSchema:A,abilities:ne.abilities[A.tsName].filter(a)});let V=ne.abilities[A.tsName].filter(a,{inject:{where:j.where,limit:j.limit}}).query[pe];return j.offset&&(V.offset=j.offset),j.orderBy&&(V.orderBy=j.orderBy),V}}),E},{});return {...R,...I,...D}}})};var Pr=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}OrderInputArgument`,Qt=({db:e,schemaBuilder:t})=>{let n=new Map,r=G(()=>t.enumType("SortingParameter",{values:["asc","desc"]})),o=({table:i,refName:s,dbName:l})=>{let u=_({db:e,dbName:l,tsName:i}),p=s??Pr(u.tsName),a=n.get(p);return a||(a=t.inputType(p,{fields:c=>{let x=Object.entries(u.columns).reduce((y,[T])=>(y[T]=c.field({type:r(),required:false}),y),{}),h=Object.entries(u.relations??{}).reduce((y,[T,N])=>{let g=_({db:e,table:N.targetTable}),D=o({dbName:g.dbName});return y[T]=c.field({type:D,required:false}),y},{});return {...x,...h}}}),n.set(p,a),a)};return o};var Fr="RUMBLE_SUBSCRIPTION_NOTIFICATION",jr="REMOVED",_r="UPDATED",Qr="CREATED",qt=({subscriptions:e})=>{let t=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:t,makePubSubInstance:({table:r})=>{function o({action:i,tableName:s,primaryKeyValue:l}){let u;switch(i){case "created":u=Qr;break;case "removed":u=jr;break;case "updated":u=_r;break;default:throw new Error(`Unknown action: ${i}`)}return `${Fr}/${s}${l?`/${l}`:""}/${u}`}return {registerOnInstance({instance:i,action:s,primaryKeyValue:l}){let u=o({tableName:r.toString(),action:s,primaryKeyValue:l});i.register(u);},created(){let i=o({tableName:r.toString(),action:"created"});return t.publish(i)},removed(){let i=o({tableName:r.toString(),action:"removed"});return t.publish(i)},updated(i){let l=(Array.isArray(i)?i:[i]).map(p=>o({tableName:r.toString(),action:"updated",primaryKeyValue:p})),u=Array.from(new Set(l));for(let p of u)t.publish(p);}}}}};var Gt=({db:e,schemaBuilder:t,search:n,whereArgImplementer:r,orderArgImplementer:o,makePubSubInstance:i})=>({table:s,readAction:l="read",listAction:u="read"})=>{let p=r({table:s}),a=o({table:s}),m=_({db:e,tsName:s}),c=Object.values(m.primaryColumns)[0],{registerOnInstance:x}=i({table:s});return t.queryFields(h=>{let y={where:h.arg({type:p,required:false}),orderBy:h.arg({type:a,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false}),search:h.arg.string({required:false})};return n?.enabled||delete y.search,{[pluralize.plural(s.toString())]:h.drizzleField({type:[s],nullable:false,smartSubscription:true,description:`List all ${pluralize.plural(s.toString())}`,subscribe:(T,N,g,D,R)=>{x({instance:T,action:"created"}),x({instance:T,action:"removed"});},args:y,resolve:(T,N,g,D,R)=>{g=JSON.parse(JSON.stringify(g)),Ie({search:n,args:g,tableSchema:m,abilities:D.abilities[s].filter(u)});let I=D.abilities[s].filter(u,g.where||g.limit||g.offset?{inject:{where:g.where,limit:g.limit}}:void 0).query.many;g.offset&&(I.offset=g.offset),g.orderBy&&(I.orderBy=g.orderBy);let E=T(I);return I.columns&&(E.columns=I.columns),e.query[s].findMany(E)}}),[pluralize.singular(s.toString())]:h.drizzleField({type:s,nullable:false,smartSubscription:true,description:`Get a single ${pluralize.singular(s.toString())} by ID`,args:{id:h.arg.id({required:true})},resolve:(T,N,g,D,R)=>{g=JSON.parse(JSON.stringify(g));let I=D.abilities[s].filter(l,{inject:{where:{[c.name]:g.id}}}).query.single,E=T(I);return I.columns&&(E.columns=I.columns),e.query[s].findFirst(E).then(Ke)}})}})};var Vt="ManualFiltersPlugin",Mt=Vt,$t="applyFilters",He=class extends kr.BasePlugin{wrapResolve(t,n){return async(r,o,i,s)=>{let l,u=n?.type;if(u.kind==="List"?l=u.type?.ref.currentConfig.pothosOptions[$t]:u.kind==="Object"&&(l=u.ref.currentConfig.pothosOptions[$t]),!l||!Array.isArray(l)||l.length===0)return t(r,o,i,s);let p=await t(r,o,i,s),a=Array.isArray(p)?p:[p],m=Array.isArray(l)?l:[l],c=await Ct({filters:m,entities:a,context:i});return Array.isArray(p)?c:c[0]??null}}};kr__default.default.registerPlugin(Vt,He);var Gr=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}WhereInputArgument`,Wt=({db:e,schemaBuilder:t,enumImplementer:n})=>{let r=new Map,o=({table:i,refName:s,dbName:l})=>{let u=_({db:e,dbName:l,tsName:i}),p=s??Gr(u.tsName),a=r.get(p);return a||(a=t.inputType(p,{fields:c=>{let x=(T,N)=>{let g=Ce({sqlType:T,fieldName:N});switch(g){case "Int":return c.field({type:"IntWhereInputArgument"});case "String":return c.field({type:"StringWhereInputArgument"});case "Boolean":return c.boolean({required:false});case "Date":return c.field({type:"DateWhereInputArgument"});case "DateTime":return c.field({type:"DateWhereInputArgument"});case "Float":return c.field({type:"FloatWhereInputArgument"});case "ID":return c.id({required:false});case "JSON":return c.field({type:"JSON",required:false});default:throw new O(`Unsupported argument type ${g} for column ${T}`)}},h=Object.entries(u.columns).reduce((T,[N,g])=>{if(Ae(g)){let D=n({enumColumn:g});T[N]=c.field({type:D,required:false});}else T[N]=x(g.getSQLType(),N);return T},{}),y=Object.entries(u.relations??{}).reduce((T,[N,g])=>{let D=_({db:e,table:g.targetTable}),R=o({dbName:D.dbName});return T[N]=c.field({type:R,required:false}),T},{});return {...h,...y}}}),r.set(p,a),a)};return o};function Jt(e){let t=e.inputRef("IntWhereInputArgument").implement({fields:i=>({eq:i.int(),ne:i.int(),gt:i.int(),gte:i.int(),lt:i.int(),lte:i.int(),in:i.intList(),notIn:i.intList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.intList(),arrayContained:i.intList(),arrayContains:i.intList(),AND:i.field({type:[t]}),OR:i.field({type:[t]}),NOT:i.field({type:t})})}),n=e.inputRef("FloatWhereInputArgument").implement({fields:i=>({eq:i.float(),ne:i.float(),gt:i.float(),gte:i.float(),lt:i.float(),lte:i.float(),in:i.floatList(),notIn:i.floatList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.floatList(),arrayContained:i.floatList(),arrayContains:i.floatList(),AND:i.field({type:[n]}),OR:i.field({type:[n]}),NOT:i.field({type:n})})}),r=e.inputRef("StringWhereInputArgument").implement({fields:i=>({eq:i.string(),ne:i.string(),gt:i.string(),gte:i.string(),lt:i.string(),lte:i.string(),in:i.stringList(),notIn:i.stringList(),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.stringList(),arrayContained:i.stringList(),arrayContains:i.stringList(),AND:i.field({type:[r]}),OR:i.field({type:[r]}),NOT:i.field({type:r})})}),o=e.inputRef("DateWhereInputArgument").implement({fields:i=>({eq:i.field({type:"Date"}),ne:i.field({type:"Date"}),gt:i.field({type:"Date"}),gte:i.field({type:"Date"}),lt:i.field({type:"Date"}),lte:i.field({type:"Date"}),in:i.field({type:["Date"]}),notIn:i.field({type:["Date"]}),like:i.string(),ilike:i.string(),notLike:i.string(),notIlike:i.string(),isNull:i.boolean(),isNotNull:i.boolean(),arrayOverlaps:i.field({type:["Date"]}),arrayContained:i.field({type:["Date"]}),arrayContains:i.field({type:["Date"]}),AND:i.field({type:[o]}),OR:i.field({type:[o]}),NOT:i.field({type:o})})});}var Kt=({db:e,disableDefaultObjects:t,pubsub:n,pothosConfig:r})=>{let o=new kr__default.default({...r,plugins:[Mt,Vr__default.default,Mr__default.default,...r?.plugins??[]],drizzle:{client:e,relations:e._.relations,getTableConfig(i){return {columns:Object.values(i[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(i[Symbol.for("drizzle:Columns")]).filter(s=>s.primary)}}},smartSubscriptions:{...Mr.subscribeOptionsFromIterator((i,s)=>n.subscribe(i))}});return o.addScalarType("JSON",graphqlScalars.JSONResolver),o.addScalarType("Date",graphqlScalars.DateResolver),o.addScalarType("DateTime",graphqlScalars.DateTimeISOResolver),Jt(o),t?.query||o.queryType({}),t?.subscription||o.subscriptionType({}),t?.mutation||o.mutationType({}),{schemaBuilder:o}};var ni=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&jt(e.db);let t=vt(e),n=Lt({...e,abilityBuilder:t}),{makePubSubInstance:r,pubsub:o}=qt({...e}),{schemaBuilder:i}=Kt({...e,pubsub:o}),s=Bt({...e,schemaBuilder:i}),l=Wt({...e,schemaBuilder:i,enumImplementer:s}),u=Qt({...e,schemaBuilder:i}),p=_t({...e,schemaBuilder:i,makePubSubInstance:r,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:s,abilityBuilder:t}),a=Gt({...e,schemaBuilder:i,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:r}),m=G(()=>i.toSchema()),c=y=>{let T=y?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return graphqlYoga.createYoga({...y,graphiql:T,plugins:[...y?.plugins??[],...T?[]:[pluginDisableIntrospection.useDisableIntrospection(),graphqlArmor.EnvelopArmorPlugin()]].filter(Boolean),schema:m(),context:n})},x=y=>(y.openAPI&&esToolkit.merge(y.openAPI,wt),sofaApi.useSofa({...y,schema:m(),context:n})),h=Ot({...e,builtSchema:m});return {abilityBuilder:t,schemaBuilder:i,createYoga:c,createSofa:x,object:p,whereArg:l,orderArg:u,query:a,pubsub:r,enum_:s,clientCreator:h}};exports.RumbleError=O;exports.RumbleErrorSafe=te;exports.assertFindFirstExists=Ke;exports.assertFirstEntryExists=yr;exports.generateFromSchema=Me;exports.makeLiveQuery=cr;exports.makeMutation=mr;exports.makeQuery=fr;exports.makeSubscription=dr;exports.mapNullFieldsToUndefined=hr;exports.rumble=ni;//# sourceMappingURL=index.cjs.map
9
105
  //# sourceMappingURL=index.cjs.map