@m1212e/rumble 0.9.0 → 0.10.1

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/index.d.cts CHANGED
@@ -105,6 +105,65 @@ declare const assertFindFirstExists: <T>(value: T | undefined) => T;
105
105
  * ```
106
106
  */
107
107
  declare const assertFirstEntryExists: <T>(value: T[]) => T;
108
+ /**
109
+ * Helper to map null fields to undefined
110
+ * @param obj The object to map
111
+ * @returns The mapped object with all fields of 'null' transformed to 'undefined'
112
+ *
113
+ * This becomes useful for update mutations where you do not want to pass null (unset value in db)
114
+ * but undefined (do not touch value in db) in case of a value not beeing set in the args of said mutation
115
+ * @example
116
+ * ```ts
117
+ * updateUser: t.drizzleField({
118
+ type: User,
119
+ args: {
120
+ id: t.arg.string({ required: true }),
121
+ email: t.arg.string(),
122
+ lastName: t.arg.string(),
123
+ firstName: t.arg.string(),
124
+ },
125
+ resolve: async (query, root, args, ctx, info) => {
126
+ const mappedArgs = mapNullFieldsToUndefined(args);
127
+ const user = await db.transaction(async (tx) => {
128
+ const user = await tx
129
+ .update(schema.user)
130
+ .set({
131
+
132
+ // email: args.email ?? undefined,
133
+ // lastName: args.lastName ?? undefined,
134
+ // firstName: args.firstName ?? undefined,
135
+
136
+ // becomes this
137
+
138
+ email: mappedArgs.email,
139
+ lastName: mappedArgs.lastName,
140
+ firstName: mappedArgs.firstName,
141
+ })
142
+ .returning()
143
+ .then(assertFirstEntryExists);
144
+ return user;
145
+ });
146
+
147
+ pubsub.updated(user.id);
148
+
149
+ return db.query.user
150
+ .findFirst(
151
+ query(
152
+ ctx.abilities.user.filter('read', {
153
+ inject: {
154
+ where: { id: user.id },
155
+ },
156
+ }).query.single,
157
+ ),
158
+ )
159
+ .then(assertFindFirstExists);
160
+ },
161
+ }),
162
+ *
163
+ *
164
+ * ```
165
+ */
166
+ declare function mapNullFieldsToUndefined<T extends object>(obj: T): { [K in keyof T]: T[K] extends null ? undefined : T[K]; };
108
167
 
109
168
  type QueryFilterObject = Partial<{
110
169
  where: any;
@@ -724,4 +783,4 @@ declare class RumbleError extends Error {
724
783
  declare class RumbleErrorSafe extends GraphQLError {
725
784
  }
726
785
 
727
- export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, rumble };
786
+ export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, mapNullFieldsToUndefined, rumble };
package/index.d.ts CHANGED
@@ -105,6 +105,65 @@ declare const assertFindFirstExists: <T>(value: T | undefined) => T;
105
105
  * ```
106
106
  */
107
107
  declare const assertFirstEntryExists: <T>(value: T[]) => T;
108
+ /**
109
+ * Helper to map null fields to undefined
110
+ * @param obj The object to map
111
+ * @returns The mapped object with all fields of 'null' transformed to 'undefined'
112
+ *
113
+ * This becomes useful for update mutations where you do not want to pass null (unset value in db)
114
+ * but undefined (do not touch value in db) in case of a value not beeing set in the args of said mutation
115
+ * @example
116
+ * ```ts
117
+ * updateUser: t.drizzleField({
118
+ type: User,
119
+ args: {
120
+ id: t.arg.string({ required: true }),
121
+ email: t.arg.string(),
122
+ lastName: t.arg.string(),
123
+ firstName: t.arg.string(),
124
+ },
125
+ resolve: async (query, root, args, ctx, info) => {
126
+ const mappedArgs = mapNullFieldsToUndefined(args);
127
+ const user = await db.transaction(async (tx) => {
128
+ const user = await tx
129
+ .update(schema.user)
130
+ .set({
131
+
132
+ // email: args.email ?? undefined,
133
+ // lastName: args.lastName ?? undefined,
134
+ // firstName: args.firstName ?? undefined,
135
+
136
+ // becomes this
137
+
138
+ email: mappedArgs.email,
139
+ lastName: mappedArgs.lastName,
140
+ firstName: mappedArgs.firstName,
141
+ })
142
+ .returning()
143
+ .then(assertFirstEntryExists);
144
+ return user;
145
+ });
146
+
147
+ pubsub.updated(user.id);
148
+
149
+ return db.query.user
150
+ .findFirst(
151
+ query(
152
+ ctx.abilities.user.filter('read', {
153
+ inject: {
154
+ where: { id: user.id },
155
+ },
156
+ }).query.single,
157
+ ),
158
+ )
159
+ .then(assertFindFirstExists);
160
+ },
161
+ }),
162
+ *
163
+ *
164
+ * ```
165
+ */
166
+ declare function mapNullFieldsToUndefined<T extends object>(obj: T): { [K in keyof T]: T[K] extends null ? undefined : T[K]; };
108
167
 
109
168
  type QueryFilterObject = Partial<{
110
169
  where: any;
@@ -724,4 +783,4 @@ declare class RumbleError extends Error {
724
783
  declare class RumbleErrorSafe extends GraphQLError {
725
784
  }
726
785
 
727
- export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, rumble };
786
+ export { RumbleError, RumbleErrorSafe, assertFindFirstExists, assertFirstEntryExists, mapNullFieldsToUndefined, rumble };
package/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn}from'drizzle-orm/pg-core';import qe,{BasePlugin}from'@pothos/core';import je from'@pothos/plugin-drizzle';import Ge,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function J(t){return typeof t=="object"&&t!==null}function H(t,n){throw new Error("Unexpected invariant triggered.")}var be=/\r\n|[\n\r]/g;function U(t,n){let o=0,p=1;for(let i of t.body.matchAll(be)){if(typeof i.index=="number"||H(),i.index>=n)break;o=i.index+i[0].length,p+=1;}return {line:p,column:n+1-o}}function X(t){return K(t.source,U(t.source,t.start))}function K(t,n){let o=t.locationOffset.column-1,p="".padStart(o)+t.body,i=n.line-1,e=t.locationOffset.line-1,c=n.line+e,l=n.line===1?o:0,u=n.column+l,y=`${t.name}:${c}:${u}
2
- `,a=p.split(/\r\n|[\n\r]/g),d=a[i];if(d.length>120){let s=Math.floor(u/80),C=u%80,r=[];for(let g=0;g<d.length;g+=80)r.push(d.slice(g,g+80));return y+Y([[`${c} |`,r[0]],...r.slice(1,s+1).map(g=>["|",g]),["|","^".padStart(C)],["|",r[s+1]]])}return y+Y([[`${c-1} |`,a[i-1]],[`${c} |`,d],["|","^".padStart(u)],[`${c+1} |`,a[i+1]]])}function Y(t){let n=t.filter(([p,i])=>i!==void 0),o=Math.max(...n.map(([p])=>p.length));return n.map(([p,i])=>p.padStart(o)+(i?" "+i:"")).join(`
3
- `)}function he(t){let n=t[0];return n==null||"kind"in n||"length"in n?{nodes:n,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:n}var L=class t extends Error{constructor(n,...o){var p,i,e;let{nodes:c,source:l,positions:u,path:y,originalError:a,extensions:d}=he(o);super(n),this.name="GraphQLError",this.path=y??void 0,this.originalError=a??void 0,this.nodes=Z(Array.isArray(c)?c:c?[c]:void 0);let s=Z((p=this.nodes)===null||p===void 0?void 0:p.map(r=>r.loc).filter(r=>r!=null));this.source=l??(s==null||(i=s[0])===null||i===void 0?void 0:i.source),this.positions=u??s?.map(r=>r.start),this.locations=u&&l?u.map(r=>U(l,r)):s?.map(r=>U(r.source,r.start));let C=J(a?.extensions)?a?.extensions:void 0;this.extensions=(e=d??C)!==null&&e!==void 0?e: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,t):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 o of this.nodes)o.loc&&(n+=`
1
+ import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn}from'drizzle-orm/pg-core';import {singular,plural}from'pluralize';import we,{BasePlugin}from'@pothos/core';import Ke from'@pothos/plugin-drizzle';import _e,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function J(t){return typeof t=="object"&&t!==null}function H(t,n){throw new Error("Unexpected invariant triggered.")}var be=/\r\n|[\n\r]/g;function U(t,n){let r=0,p=1;for(let i of t.body.matchAll(be)){if(typeof i.index=="number"||H(),i.index>=n)break;r=i.index+i[0].length,p+=1;}return {line:p,column:n+1-r}}function X(t){return _(t.source,U(t.source,t.start))}function _(t,n){let r=t.locationOffset.column-1,p="".padStart(r)+t.body,i=n.line-1,e=t.locationOffset.line-1,c=n.line+e,l=n.line===1?r:0,u=n.column+l,y=`${t.name}:${c}:${u}
2
+ `,s=p.split(/\r\n|[\n\r]/g),d=s[i];if(d.length>120){let a=Math.floor(u/80),h=u%80,o=[];for(let b=0;b<d.length;b+=80)o.push(d.slice(b,b+80));return y+Y([[`${c} |`,o[0]],...o.slice(1,a+1).map(b=>["|",b]),["|","^".padStart(h)],["|",o[a+1]]])}return y+Y([[`${c-1} |`,s[i-1]],[`${c} |`,d],["|","^".padStart(u)],[`${c+1} |`,s[i+1]]])}function Y(t){let n=t.filter(([p,i])=>i!==void 0),r=Math.max(...n.map(([p])=>p.length));return n.map(([p,i])=>p.padStart(r)+(i?" "+i:"")).join(`
3
+ `)}function he(t){let n=t[0];return n==null||"kind"in n||"length"in n?{nodes:n,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:n}var L=class t extends Error{constructor(n,...r){var p,i,e;let{nodes:c,source:l,positions:u,path:y,originalError:s,extensions:d}=he(r);super(n),this.name="GraphQLError",this.path=y??void 0,this.originalError=s??void 0,this.nodes=Z(Array.isArray(c)?c:c?[c]:void 0);let a=Z((p=this.nodes)===null||p===void 0?void 0:p.map(o=>o.loc).filter(o=>o!=null));this.source=l??(a==null||(i=a[0])===null||i===void 0?void 0:i.source),this.positions=u??a?.map(o=>o.start),this.locations=u&&l?u.map(o=>U(l,o)):a?.map(o=>U(o.source,o.start));let h=J(s?.extensions)?s?.extensions:void 0;this.extensions=(e=d??h)!==null&&e!==void 0?e: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}}),s!=null&&s.stack?Object.defineProperty(this,"stack",{value:s.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,t):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+=`
4
4
 
5
- `+X(o.loc));else if(this.source&&this.locations)for(let o of this.locations)n+=`
5
+ `+X(r.loc));else if(this.source&&this.locations)for(let r of this.locations)n+=`
6
6
 
7
- `+K(this.source,o);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 Z(t){return t===void 0||t.length===0?void 0:t}var S=class extends Error{constructor(n){super(n),this.name="RumbleError";}},w=class extends L{};var V=t=>{if(!t)throw new w("Value not found but required (findFirst)");return t},Ce=t=>{let n=t.at(0);if(!n)throw new w("Value not found but required (firstEntry)");return n},ee=async({filters:t,entities:n,context:o})=>(await Promise.all(t.map(p=>p({context:o,entities:n})))).reduce((p,i)=>(p.push(...i),p),[]);function v(t){let n,o=false;return ()=>(o||(n=t(),o=true),n)}var G=(t,n)=>new S(`RumbleError: Unknown SQL type '${t}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function te(t){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(t))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(t))return {value1:"a",value2:"b"};if(["uuid"].includes(t))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(t))return {value1:true,value2:false};if(["timestamp","datetime"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(t))return {value1:{a:1},value2:{b:2}};throw G(t,"Distinct")}var M=Symbol.for("drizzle:Name"),ne=Symbol.for("drizzle:Columns");function E({dbName:t,tsName:n,table:o,db:p}){let i=o;if(n&&(i=p._.relations.schema[n]),t&&(i=Object.values(p._.relations.schema).find(e=>e[M]===t)),!i)throw new S(`Could not find schema for ${JSON.stringify({tsName:n,dbName:t,table:o?.[M]}).toString()}`);return {tableSchema:i,columns:i[ne],get primaryColumns(){return Object.entries(i[ne]).filter(([e,c])=>c.primary).reduce((e,[c,l])=>(e[c]=l,e),{})},relations:p._.relations.config[n],dbName:i[M],get tsName(){return Object.entries(p._.relations.schema).find(([e,c])=>c===i).at(0)}}}function Re(t){return typeof t!="function"}function Se(t){return typeof t=="function"&&t.constructor.name!=="AsyncFunction"}var re=({db:t,actions:n,defaultLimit:o})=>{let p={},i={},e={},c=l=>{for(let u of n)e[l]||(e[l]={}),e[l][u]||(e[l][u]=[]);return {allow:u=>{let y=i[l];y||(y={},i[l]=y);let a=Array.isArray(u)?u:[u];for(let d of a){let s=y[d];s||(s="unspecified",y[d]=s);}return {when:d=>{for(let s of a)y[s]==="unspecified"&&(y[s]=[]),y[s].push(d);}}},filter:u=>{let y=Array.isArray(u)?u:[u];return {by:a=>{for(let d of y)e[l][d].push(a);}}}}};for(let l of Object.keys(t.query))p[l]=c(l);return {...p,registeredQueryFilters:i,registeredFilters:e,buildWithUserContext:l=>{let u={},y=a=>({filter:(d,s)=>{let C=m=>{let x=v(()=>{if(!(!m?.where&&!s?.inject?.where)){if(s?.inject?.where&&m?.where)return {AND:[m?.where,s?.inject?.where]};if(s?.inject?.where&&!m?.where)return s?.inject?.where;if(!s?.inject?.where&&m?.where)return m?.where;!s?.inject?.where&&m?.where;}}),P=v(()=>{let A=x();if(!A)return;let Q=E({tsName:a,db:t});return relationsFilterToSQL(Q.tableSchema,A)}),k=v(()=>{let A=m?.limit??o;return s?.inject?.limit&&(!A||A>s.inject.limit)&&(A=s.inject.limit),m?.limit&&(!A||m.limit>A)&&(A=m.limit),A??void 0}),O=v(()=>{if(!(!m?.columns&&!s?.inject?.columns))return {...m?.columns,...s?.inject?.columns}}),q={query:{single:{get where(){return x()},columns:O()},many:{get where(){return x()},columns:O(),get limit(){return k()}}},sql:{get where(){return P()},columns:O(),get limit(){return k()}}};return O()||(delete q.sql.columns,delete q.query.many.columns,delete q.query.single.columns),q},r=()=>{let m=E({db:t,tsName:a});if(Object.keys(m.primaryColumns).length===0)throw new S(`No primary key found for entity ${a.toString()}`);let x=Object.values(m.primaryColumns)[0],P=te(x.getSQLType());return {where:{AND:[{[x.name]:P.value1},{[x.name]:P.value2}]}}},g=i?.[a]?.[d];if(g==="unspecified")return C();g||(g=[r()]);let D=g.filter(Re),b=g.filter(Se).map(m=>m(l)),h=b.some(m=>m==="allow"),I=[...D,...b].filter(m=>m!==void 0).filter(m=>m!=="allow");!h&&I.length===0&&(I=[r()]);let F;for(let m of I)m?.limit&&(F===void 0||m.limit>F)&&(F=m.limit);let R;for(let m of [...I,s?.inject])m?.columns&&(R===void 0?R=m.columns:R={...R,...m.columns});let f=h?[]:I.filter(m=>m?.where).map(m=>m.where),T=f.length>0?{OR:f}:void 0;return C({where:T,columns:R,limit:F})},explicitFilters:d=>e[a][d]});for(let a of Object.keys(t.query))u[a]=y(a);return u}}};var ie=({context:t,abilityBuilder:n})=>async o=>{let p=t?await t(o):{};return {...p,abilities:n.buildWithUserContext(p)}};function N(t){return String(t).charAt(0).toUpperCase()+String(t).slice(1)}function W(t){return t instanceof PgEnumColumn}var oe=({db:t,schemaBuilder:n})=>{let o=new Map;return ({tsName:i,enumColumn:e,refName:c})=>{let l,u;if(i){let s=t._.relations.schema[i];l=i.toString();let C=Object.values(t._.relations.schema).filter(r=>typeof r=="object").map(r=>Object.values(r[Symbol.for("drizzle:Columns")])).flat(2).find(r=>r.config?.enum===s);if(!C)throw new S(`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!`);u=C.enumValues;}else if(e){let s=Object.entries(t._.relations.schema).find(([C,r])=>r===e.config.enum);if(!s)throw new S(`Could not find enum in schema for ${e.name}!`);l=s[0],u=e.enumValues;}if(!l||!u)throw new S("Could not determine enum structure!");let y=c??`${N(toCamelCase(l))}Enum`,a=o.get(y);return a||(a=n.enumType(y,{values:u}),o.set(y,a),a)}};var se={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"}}}}}};function _({sqlType:t,fieldName:n}){let o;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t)&&(o="Int"),["real","decimal","double","float"].includes(t)&&(o="Float"),["string","text","varchar","char","text(256)"].includes(t)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?o="ID":o="String"),["uuid"].includes(t)&&(o="ID"),["boolean"].includes(t)&&(o="Boolean"),["timestamp","datetime"].includes(t)&&(o="DateTime"),["date"].includes(t)&&(o="Date"),["json"].includes(t)&&(o="JSON"),o!==void 0)return o;throw G(t,"SQL to GQL")}var Ee=t=>typeof t!="object"?false:!!Object.keys(t).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(o=>o===n)),ae=({db:t,schemaBuilder:n,makePubSubInstance:o,whereArgImplementer:p,orderArgImplementer:i,enumImplementer:e,abilityBuilder:c})=>({table:l,refName:u,readAction:y="read",adjust:a})=>{let d=E({db:t,tsName:l});Object.keys(d.primaryColumns).length===0&&console.warn(`Could not find primary key for ${l.toString()}. Cannot register subscriptions!`);let s=Object.values(d.primaryColumns)[0],{registerOnInstance:C}=o({table:l});return n.drizzleObject(l,{name:u??N(l.toString()),subscribe:(r,g,D)=>{if(!s)return;let b=g[s.name];if(!b){console.warn(`Could not find primary key value for ${JSON.stringify(g)}. Cannot register subscription!`);return}C({instance:r,action:"updated",primaryKeyValue:b});},applyFilters:c?.registeredFilters?.[l]?.[y],fields:r=>{let g=d.columns,D=(R,f,T)=>{let m=_({sqlType:R,fieldName:f});switch(m){case "Int":return r.exposeInt(f,{nullable:T});case "String":return r.exposeString(f,{nullable:T});case "Boolean":return r.exposeBoolean(f,{nullable:T});case "Date":return r.field({type:"Date",resolve:x=>x[f],nullable:T});case "DateTime":return r.field({type:"DateTime",resolve:x=>x[f],nullable:T});case "Float":return r.exposeFloat(f,{nullable:T});case "ID":return r.exposeID(f,{nullable:T});case "JSON":return r.field({type:"JSON",resolve:x=>x[f],nullable:T});default:throw new S(`Unsupported object type ${m} for column ${f}`)}},b=new Map,h=a?.(new Proxy(r,{get:(R,f)=>typeof R[f]=="function"?(...T)=>{let m=R[f](...T),x=T.find(Ee);if(!x)throw new S("Expected config object to be passed to adjust field");return b.set(m,{params:T,creatorFunction:R[f],configObject:x}),m}:R[f]}))??{},I=Object.entries(g).reduce((R,[f,T])=>{if(h[f]){let{params:m,creatorFunction:x,configObject:P}=b.get(h[f]);return typeof P.nullable!="boolean"&&(P.nullable=!T.notNull),h[f]=x.bind(r)(...m),R}if(W(T)){let m=e({enumColumn:T});R[f]=r.field({type:m,resolve:x=>x[f],nullable:!T.notNull});}else R[f]=D(T.getSQLType(),f,!T.notNull);return R},{}),F=Object.entries(d.relations??{}).reduce((R,[f,T])=>{let m=E({db:t,table:T.targetTable}),x=p({dbName:m.dbName}),P=i({dbName:m.dbName}),k=o({table:m.tsName}),O=false,q=true,A="many";T instanceof One&&(q=false,O=T.optional,A="single");let Q=(B,j)=>{k.registerOnInstance({instance:B,action:"created"}),k.registerOnInstance({instance:B,action:"removed"});};if(h[f]){let{params:B,creatorFunction:j,configObject:z}=b.get(h[f]);return typeof z.nullable!="boolean"&&(z.nullable=O),typeof z.subscribe!="function"&&(z.subscribe=Q),h[f]=j.bind(r)(...B),R}return R[f]=r.relation(f,{args:{where:r.arg({type:x,required:false}),orderBy:r.arg({type:P,required:false}),...q?{offset:r.arg.int({required:false}),limit:r.arg.int({required:false})}:{}},subscribe:Q,nullable:O,query:(B,j)=>{B=JSON.parse(JSON.stringify(B));let z=j.abilities[m.tsName].filter(y,{inject:{where:B.where,limit:B.limit}}).query[A];return B.offset&&(z.offset=B.offset),B.orderBy&&(z.orderBy=B.orderBy),z}}),R},{});return {...I,...F,...h}}})};var Pe=t=>`${N(toCamelCase(t.toString()))}OrderInputArgument`,le=({db:t,schemaBuilder:n})=>{let o=new Map,p=v(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:e,refName:c,dbName:l})=>{let u=E({db:t,dbName:l,tsName:e}),y=c??Pe(u.tsName),a=o.get(y);return a||(a=n.inputType(y,{fields:s=>{let C=Object.entries(u.columns).reduce((g,[D,b])=>(g[D]=s.field({type:p(),required:false}),g),{}),r=Object.entries(u.relations??{}).reduce((g,[D,b])=>{let h=E({db:t,table:b.targetTable}),I=i({dbName:h.dbName});return g[D]=s.field({type:I,required:false}),g},{});return {...C,...r}}}),o.set(y,a),a)};return i};var ve="RUMBLE_SUBSCRIPTION_NOTIFICATION",Fe="REMOVED",Oe="UPDATED",ze="CREATED",pe=({subscriptions:t,db:n})=>{let o=t?createPubSub(...t):createPubSub();return {pubsub:o,makePubSubInstance:({table:i})=>{function e({action:c,tableName:l,primaryKeyValue:u}){let y;switch(c){case "created":y=ze;break;case "removed":y=Fe;break;case "updated":y=Oe;break;default:throw new Error(`Unknown action: ${c}`)}return `${ve}/${l}${u?`/${u}`:""}/${y}`}return {registerOnInstance({instance:c,action:l,primaryKeyValue:u}){let y=e({tableName:i.toString(),action:l,primaryKeyValue:u});c.register(y);},created(){let c=e({tableName:i.toString(),action:"created"});return o.publish(c)},removed(c){let l=e({tableName:i.toString(),action:"removed"});return o.publish(l)},updated(c){let u=(Array.isArray(c)?c:[c]).map(a=>e({tableName:i.toString(),action:"updated",primaryKeyValue:a})),y=Array.from(new Set(u));for(let a of y)o.publish(a);}}}}};var me=({db:t,schemaBuilder:n,whereArgImplementer:o,orderArgImplementer:p,makePubSubInstance:i})=>({table:e,readAction:c="read",listAction:l="read"})=>{let u=o({table:e}),y=p({table:e}),{registerOnInstance:a}=i({table:e});return n.queryFields(d=>({[`findMany${N(e.toString())}`]:d.drizzleField({type:[e],nullable:false,smartSubscription:true,subscribe:(s,C,r,g,D)=>{a({instance:s,action:"created"}),a({instance:s,action:"removed"});},args:{where:d.arg({type:u,required:false}),orderBy:d.arg({type:y,required:false}),limit:d.arg.int({required:false}),offset:d.arg.int({required:false})},resolve:(s,C,r,g,D)=>{r=JSON.parse(JSON.stringify(r));let b=g.abilities[e].filter(l,r.where||r.limit||r.offset?{inject:{where:r.where,limit:r.limit}}:void 0).query.many;r.offset&&(b.offset=r.offset),r.orderBy&&(b.orderBy=r.orderBy);let h=s(b);return b.columns&&(h.columns=b.columns),t.query[e].findMany(h)}}),[`findFirst${N(e.toString())}`]:d.drizzleField({type:e,nullable:false,smartSubscription:true,args:{where:d.arg({type:u,required:false})},resolve:(s,C,r,g,D)=>{r=JSON.parse(JSON.stringify(r));let b=g.abilities[e].filter(c,r.where?{inject:{where:r.where}}:void 0).query.single,h=s(b);return b.columns&&(h.columns=b.columns),t.query[e].findFirst(h).then(V)}})}))};var ce="ManualFiltersPlugin",ye=ce,we="applyFilters",$=class extends BasePlugin{wrapResolve(n,o){return async(p,i,e,c)=>{let l=(o?.type).type?.ref.currentConfig.pothosOptions[we];if(!l||!Array.isArray(l)||l.length===0)return n(p,i,e,c);let u=await n(p,i,e,c),y=Array.isArray(u)?u:[u],a=Array.isArray(l)?l:[l],d=await ee({filters:a,entities:y,context:e});return Array.isArray(u)?d:d[0]??null}}};qe.registerPlugin(ce,$);var Ue=t=>`${N(toCamelCase(t.toString()))}WhereInputArgument`,de=({db:t,schemaBuilder:n,enumImplementer:o})=>{let p=new Map,i=({table:e,refName:c,dbName:l})=>{let u=E({db:t,dbName:l,tsName:e}),y=c??Ue(u.tsName),a=p.get(y);return a||(a=n.inputType(y,{fields:s=>{let C=(D,b)=>{let h=_({sqlType:D,fieldName:b});switch(h){case "Int":return s.field({type:"IntWhereInputArgument"});case "String":return s.field({type:"StringWhereInputArgument"});case "Boolean":return s.boolean({required:false});case "Date":return s.field({type:"DateWhereInputArgument"});case "DateTime":return s.field({type:"DateWhereInputArgument"});case "Float":return s.field({type:"FloatWhereInputArgument"});case "ID":return s.id({required:false});case "JSON":return s.field({type:"JSON",required:false});default:throw new S(`Unsupported argument type ${h} for column ${D}`)}},r=Object.entries(u.columns).reduce((D,[b,h])=>{if(W(h)){let I=o({enumColumn:h});D[b]=s.field({type:I,required:false});}else D[b]=C(h.getSQLType(),b);return D},{}),g=Object.entries(u.relations??{}).reduce((D,[b,h])=>{let I=E({db:t,table:h.targetTable}),F=i({dbName:I.dbName});return D[b]=s.field({type:F,required:false}),D},{});return {...r,...g}}}),p.set(y,a),a)};return i};function fe(t){let n=t.inputRef("IntWhereInputArgument").implement({fields:e=>({eq:e.int(),ne:e.int(),gt:e.int(),gte:e.int(),lt:e.int(),lte:e.int(),in:e.intList(),notIn:e.intList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.intList(),arrayContained:e.intList(),arrayContains:e.intList(),AND:e.field({type:[n]}),OR:e.field({type:[n]}),NOT:e.field({type:n})})}),o=t.inputRef("FloatWhereInputArgument").implement({fields:e=>({eq:e.float(),ne:e.float(),gt:e.float(),gte:e.float(),lt:e.float(),lte:e.float(),in:e.floatList(),notIn:e.floatList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.floatList(),arrayContained:e.floatList(),arrayContains:e.floatList(),AND:e.field({type:[o]}),OR:e.field({type:[o]}),NOT:e.field({type:o})})}),p=t.inputRef("StringWhereInputArgument").implement({fields:e=>({eq:e.string(),ne:e.string(),gt:e.string(),gte:e.string(),lt:e.string(),lte:e.string(),in:e.stringList(),notIn:e.stringList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.stringList(),arrayContained:e.stringList(),arrayContains:e.stringList(),AND:e.field({type:[p]}),OR:e.field({type:[p]}),NOT:e.field({type:p})})}),i=t.inputRef("DateWhereInputArgument").implement({fields:e=>({eq:e.field({type:"Date"}),ne:e.field({type:"Date"}),gt:e.field({type:"Date"}),gte:e.field({type:"Date"}),lt:e.field({type:"Date"}),lte:e.field({type:"Date"}),in:e.field({type:["Date"]}),notIn:e.field({type:["Date"]}),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.field({type:["Date"]}),arrayContained:e.field({type:["Date"]}),arrayContains:e.field({type:["Date"]}),AND:e.field({type:[i]}),OR:e.field({type:[i]}),NOT:e.field({type:i})})});}var ge=({db:t,disableDefaultObjects:n,pubsub:o,pothosConfig:p})=>{let i=new qe({...p,plugins:[ye,je,Ge,...p?.plugins??[]],drizzle:{client:t,relations:t._.relations,getTableConfig(e){return {columns:Object.values(e[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(e[Symbol.for("drizzle:Columns")]).filter(c=>c.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((e,c)=>o.subscribe(e))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),fe(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var Je=t=>{t.actions||(t.actions=["read","update","delete"]),t.defaultLimit===void 0&&(t.defaultLimit=100);let n=re(t),o=ie({...t,abilityBuilder:n}),{makePubSubInstance:p,pubsub:i}=pe({...t}),{schemaBuilder:e}=ge({...t,pubsub:i}),c=oe({...t,schemaBuilder:e}),l=de({...t,schemaBuilder:e,enumImplementer:c}),u=le({...t,schemaBuilder:e}),y=ae({...t,schemaBuilder:e,makePubSubInstance:p,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:c,abilityBuilder:n}),a=me({...t,schemaBuilder:e,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:p}),d=v(()=>e.toSchema());return {abilityBuilder:n,schemaBuilder:e,createYoga:r=>createYoga({...r,schema:d(),context:o}),createSofa:r=>(r.openAPI&&(r.openAPI={...se,...r.openAPI}),useSofa({...r,schema:d(),context:o})),object:y,whereArg:l,orderArg:u,query:a,pubsub:p,enum_:c}};export{S as RumbleError,w as RumbleErrorSafe,V as assertFindFirstExists,Ce as assertFirstEntryExists,Je as rumble};//# sourceMappingURL=index.js.map
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 Z(t){return t===void 0||t.length===0?void 0:t}var I=class extends Error{constructor(n){super(n),this.name="RumbleError";}},k=class extends L{};var V=t=>{if(!t)throw new k("Value not found but required (findFirst)");return t},Ce=t=>{let n=t.at(0);if(!n)throw new k("Value not found but required (firstEntry)");return n},ee=async({filters:t,entities:n,context:r})=>(await Promise.all(t.map(p=>p({context:r,entities:n})))).reduce((p,i)=>(p.push(...i),p),[]);function De(t){return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,r===null?void 0:r]))}function v(t){let n,r=false;return ()=>(r||(n=t(),r=true),n)}var G=(t,n)=>new I(`RumbleError: Unknown SQL type '${t}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function te(t){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(t))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(t))return {value1:"a",value2:"b"};if(["uuid"].includes(t))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(t))return {value1:true,value2:false};if(["timestamp","datetime"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(t))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(t))return {value1:{a:1},value2:{b:2}};throw G(t,"Distinct")}var M=Symbol.for("drizzle:Name"),ne=Symbol.for("drizzle:Columns");function B({dbName:t,tsName:n,table:r,db:p}){let i=r;if(n&&(i=p._.relations.schema[n]),t&&(i=Object.values(p._.relations.schema).find(e=>e[M]===t)),!i)throw new I(`Could not find schema for ${JSON.stringify({tsName:n,dbName:t,table:r?.[M]}).toString()}`);return {tableSchema:i,columns:i[ne],get primaryColumns(){return Object.entries(i[ne]).filter(([e,c])=>c.primary).reduce((e,[c,l])=>(e[c]=l,e),{})},relations:p._.relations.config[n],dbName:i[M],get tsName(){return Object.entries(p._.relations.schema).find(([e,c])=>c===i).at(0)}}}function Se(t){return typeof t!="function"}function Ie(t){return typeof t=="function"&&t.constructor.name!=="AsyncFunction"}var re=({db:t,actions:n,defaultLimit:r})=>{let p={},i={},e={},c=l=>{for(let u of n)e[l]||(e[l]={}),e[l][u]||(e[l][u]=[]);return {allow:u=>{let y=i[l];y||(y={},i[l]=y);let s=Array.isArray(u)?u:[u];for(let d of s){let a=y[d];a||(a="unspecified",y[d]=a);}return {when:d=>{for(let a of s)y[a]==="unspecified"&&(y[a]=[]),y[a].push(d);}}},filter:u=>{let y=Array.isArray(u)?u:[u];return {by:s=>{for(let d of y)e[l][d].push(s);}}}}};for(let l of Object.keys(t.query))p[l]=c(l);return {...p,registeredQueryFilters:i,registeredFilters:e,buildWithUserContext:l=>{let u={},y=s=>({filter:(d,a)=>{let h=m=>{let R=v(()=>{if(!(!m?.where&&!a?.inject?.where)){if(a?.inject?.where&&m?.where)return {AND:[m?.where,a?.inject?.where]};if(a?.inject?.where&&!m?.where)return a?.inject?.where;if(!a?.inject?.where&&m?.where)return m?.where;!a?.inject?.where&&m?.where;}}),P=v(()=>{let E=R();if(!E)return;let Q=B({tsName:s,db:t});return relationsFilterToSQL(Q.tableSchema,E)}),w=v(()=>{let E=m?.limit??r;return a?.inject?.limit&&(!E||E>a.inject.limit)&&(E=a.inject.limit),m?.limit&&(!E||m.limit>E)&&(E=m.limit),E??void 0}),F=v(()=>{if(!(!m?.columns&&!a?.inject?.columns))return {...m?.columns,...a?.inject?.columns}}),q={query:{single:{get where(){return R()},columns:F()},many:{get where(){return R()},columns:F(),get limit(){return w()}}},sql:{get where(){return P()},columns:F(),get limit(){return w()}}};return F()||(delete q.sql.columns,delete q.query.many.columns,delete q.query.single.columns),q},o=()=>{let m=B({db:t,tsName:s});if(Object.keys(m.primaryColumns).length===0)throw new I(`No primary key found for entity ${s.toString()}`);let R=Object.values(m.primaryColumns)[0],P=te(R.getSQLType());return {where:{AND:[{[R.name]:P.value1},{[R.name]:P.value2}]}}},b=i?.[s]?.[d];if(b==="unspecified")return h();b||(b=[o()]);let f=b.filter(Se),T=b.filter(Ie).map(m=>m(l)),C=T.some(m=>m==="allow"),D=[...f,...T].filter(m=>m!==void 0).filter(m=>m!=="allow");!C&&D.length===0&&(D=[o()]);let A;for(let m of D)m?.limit&&(A===void 0||m.limit>A)&&(A=m.limit);let S;for(let m of [...D,a?.inject])m?.columns&&(S===void 0?S=m.columns:S={...S,...m.columns});let g=C?[]:D.filter(m=>m?.where).map(m=>m.where),x=g.length>0?{OR:g}:void 0;return h({where:x,columns:S,limit:A})},explicitFilters:d=>e[s][d]});for(let s of Object.keys(t.query))u[s]=y(s);return u}}};var ie=({context:t,abilityBuilder:n})=>async r=>{let p=t?await t(r):{};return {...p,abilities:n.buildWithUserContext(p)}};function z(t){return String(t).charAt(0).toUpperCase()+String(t).slice(1)}function W(t){return t instanceof PgEnumColumn}var oe=({db:t,schemaBuilder:n})=>{let r=new Map;return ({tsName:i,enumColumn:e,refName:c})=>{let l,u;if(i){let a=t._.relations.schema[i];l=i.toString();let h=Object.values(t._.relations.schema).filter(o=>typeof o=="object").map(o=>Object.values(o[Symbol.for("drizzle:Columns")])).flat(2).find(o=>o.config?.enum===a);if(!h)throw new I(`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!`);u=h.enumValues;}else if(e){let a=Object.entries(t._.relations.schema).find(([h,o])=>o===e.config.enum);if(!a)throw new I(`Could not find enum in schema for ${e.name}!`);l=a[0],u=e.enumValues;}if(!l||!u)throw new I("Could not determine enum structure!");let y=c??`${z(toCamelCase(l))}Enum`,s=r.get(y);return s||(s=n.enumType(y,{values:u}),r.set(y,s),s)}};var se={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"}}}}}};function K({sqlType:t,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t)&&(r="Int"),["real","decimal","double","float"].includes(t)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(t)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(t)&&(r="ID"),["boolean"].includes(t)&&(r="Boolean"),["timestamp","datetime"].includes(t)&&(r="DateTime"),["date"].includes(t)&&(r="Date"),["json"].includes(t)&&(r="JSON"),r!==void 0)return r;throw G(t,"SQL to GQL")}var Ne=t=>typeof t!="object"?false:!!Object.keys(t).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ae=({db:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:p,orderArgImplementer:i,enumImplementer:e,abilityBuilder:c})=>({table:l,refName:u,readAction:y="read",adjust:s})=>{let d=B({db:t,tsName:l});Object.keys(d.primaryColumns).length===0&&console.warn(`Could not find primary key for ${l.toString()}. Cannot register subscriptions!`);let a=Object.values(d.primaryColumns)[0],{registerOnInstance:h}=r({table:l});return n.drizzleObject(l,{name:u??z(l.toString()),subscribe:(o,b,f)=>{if(!a)return;let T=b[a.name];if(!T){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:o,action:"updated",primaryKeyValue:T});},applyFilters:c?.registeredFilters?.[l]?.[y],fields:o=>{let b=d.columns,f=(S,g,x)=>{let m=K({sqlType:S,fieldName:g});switch(m){case "Int":return o.exposeInt(g,{nullable:x});case "String":return o.exposeString(g,{nullable:x});case "Boolean":return o.exposeBoolean(g,{nullable:x});case "Date":return o.field({type:"Date",resolve:R=>R[g],nullable:x});case "DateTime":return o.field({type:"DateTime",resolve:R=>R[g],nullable:x});case "Float":return o.exposeFloat(g,{nullable:x});case "ID":return o.exposeID(g,{nullable:x});case "JSON":return o.field({type:"JSON",resolve:R=>R[g],nullable:x});default:throw new I(`Unsupported object type ${m} for column ${g}`)}},T=new Map,C=s?.(new Proxy(o,{get:(S,g)=>typeof S[g]=="function"?(...x)=>{let m=S[g](...x),R=x.find(Ne);if(!R)throw new I("Expected config object to be passed to adjust field");return T.set(m,{params:x,creatorFunction:S[g],configObject:R}),m}:S[g]}))??{},D=Object.entries(b).reduce((S,[g,x])=>{if(C[g]){let{params:m,creatorFunction:R,configObject:P}=T.get(C[g]);return typeof P.nullable!="boolean"&&(P.nullable=!x.notNull),C[g]=R.bind(o)(...m),S}if(W(x)){let m=e({enumColumn:x});S[g]=o.field({type:m,resolve:R=>R[g],nullable:!x.notNull});}else S[g]=f(x.getSQLType(),g,!x.notNull);return S},{}),A=Object.entries(d.relations??{}).reduce((S,[g,x])=>{let m=B({db:t,table:x.targetTable}),R=p({dbName:m.dbName}),P=i({dbName:m.dbName}),w=r({table:m.tsName}),F=false,q=true,E="many";x instanceof One&&(q=false,F=x.optional,E="single");let Q=(N,j)=>{w.registerOnInstance({instance:N,action:"created"}),w.registerOnInstance({instance:N,action:"removed"});};if(C[g]){let{params:N,creatorFunction:j,configObject:O}=T.get(C[g]);return typeof O.nullable!="boolean"&&(O.nullable=F),typeof O.subscribe!="function"&&(O.subscribe=Q),C[g]=j.bind(o)(...N),S}return S[g]=o.relation(g,{args:{where:o.arg({type:R,required:false}),orderBy:o.arg({type:P,required:false}),...q?{offset:o.arg.int({required:false}),limit:o.arg.int({required:false})}:{}},subscribe:Q,nullable:F,query:(N,j)=>{N=JSON.parse(JSON.stringify(N));let O=j.abilities[m.tsName].filter(y,{inject:{where:N.where,limit:N.limit}}).query[E];return N.offset&&(O.offset=N.offset),N.orderBy&&(O.orderBy=N.orderBy),O}}),S},{});return {...D,...A,...C}}})};var ve=t=>`${z(toCamelCase(t.toString()))}OrderInputArgument`,le=({db:t,schemaBuilder:n})=>{let r=new Map,p=v(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:e,refName:c,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),y=c??ve(u.tsName),s=r.get(y);return s||(s=n.inputType(y,{fields:a=>{let h=Object.entries(u.columns).reduce((b,[f,T])=>(b[f]=a.field({type:p(),required:false}),b),{}),o=Object.entries(u.relations??{}).reduce((b,[f,T])=>{let C=B({db:t,table:T.targetTable}),D=i({dbName:C.dbName});return b[f]=a.field({type:D,required:false}),b},{});return {...h,...o}}}),r.set(y,s),s)};return i};var Fe="RUMBLE_SUBSCRIPTION_NOTIFICATION",Oe="REMOVED",ze="UPDATED",qe="CREATED",pe=({subscriptions:t,db:n})=>{let r=t?createPubSub(...t):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function e({action:c,tableName:l,primaryKeyValue:u}){let y;switch(c){case "created":y=qe;break;case "removed":y=Oe;break;case "updated":y=ze;break;default:throw new Error(`Unknown action: ${c}`)}return `${Fe}/${l}${u?`/${u}`:""}/${y}`}return {registerOnInstance({instance:c,action:l,primaryKeyValue:u}){let y=e({tableName:i.toString(),action:l,primaryKeyValue:u});c.register(y);},created(){let c=e({tableName:i.toString(),action:"created"});return r.publish(c)},removed(c){let l=e({tableName:i.toString(),action:"removed"});return r.publish(l)},updated(c){let u=(Array.isArray(c)?c:[c]).map(s=>e({tableName:i.toString(),action:"updated",primaryKeyValue:s})),y=Array.from(new Set(u));for(let s of y)r.publish(s);}}}}};var me=({db:t,schemaBuilder:n,whereArgImplementer:r,orderArgImplementer:p,makePubSubInstance:i})=>({table:e,readAction:c="read",listAction:l="read"})=>{let u=r({table:e}),y=p({table:e}),s=B({db:t,tsName:e}),d=Object.values(s.primaryColumns)[0],{registerOnInstance:a}=i({table:e});return n.queryFields(h=>({[plural(e.toString())]:h.drizzleField({type:[e],nullable:false,smartSubscription:true,subscribe:(o,b,f,T,C)=>{a({instance:o,action:"created"}),a({instance:o,action:"removed"});},args:{where:h.arg({type:u,required:false}),orderBy:h.arg({type:y,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(l,f.where||f.limit||f.offset?{inject:{where:f.where,limit:f.limit}}:void 0).query.many;f.offset&&(D.offset=f.offset),f.orderBy&&(D.orderBy=f.orderBy);let A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findMany(A)}}),[singular(e.toString())]:h.drizzleField({type:e,nullable:false,smartSubscription:true,args:{id:h.arg.id({required:true})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(c,{inject:{where:{[d.name]:f.id}}}).query.single,A=o(D);return D.columns&&(A.columns=D.columns),t.query[e].findFirst(A).then(V)}})}))};var ce="ManualFiltersPlugin",ye=ce,Qe="applyFilters",$=class extends BasePlugin{wrapResolve(n,r){return async(p,i,e,c)=>{let l=(r?.type).type?.ref.currentConfig.pothosOptions[Qe];if(!l||!Array.isArray(l)||l.length===0)return n(p,i,e,c);let u=await n(p,i,e,c),y=Array.isArray(u)?u:[u],s=Array.isArray(l)?l:[l],d=await ee({filters:s,entities:y,context:e});return Array.isArray(u)?d:d[0]??null}}};we.registerPlugin(ce,$);var Ge=t=>`${z(toCamelCase(t.toString()))}WhereInputArgument`,de=({db:t,schemaBuilder:n,enumImplementer:r})=>{let p=new Map,i=({table:e,refName:c,dbName:l})=>{let u=B({db:t,dbName:l,tsName:e}),y=c??Ge(u.tsName),s=p.get(y);return s||(s=n.inputType(y,{fields:a=>{let h=(f,T)=>{let C=K({sqlType:f,fieldName:T});switch(C){case "Int":return a.field({type:"IntWhereInputArgument"});case "String":return a.field({type:"StringWhereInputArgument"});case "Boolean":return a.boolean({required:false});case "Date":return a.field({type:"DateWhereInputArgument"});case "DateTime":return a.field({type:"DateWhereInputArgument"});case "Float":return a.field({type:"FloatWhereInputArgument"});case "ID":return a.id({required:false});case "JSON":return a.field({type:"JSON",required:false});default:throw new I(`Unsupported argument type ${C} for column ${f}`)}},o=Object.entries(u.columns).reduce((f,[T,C])=>{if(W(C)){let D=r({enumColumn:C});f[T]=a.field({type:D,required:false});}else f[T]=h(C.getSQLType(),T);return f},{}),b=Object.entries(u.relations??{}).reduce((f,[T,C])=>{let D=B({db:t,table:C.targetTable}),A=i({dbName:D.dbName});return f[T]=a.field({type:A,required:false}),f},{});return {...o,...b}}}),p.set(y,s),s)};return i};function fe(t){let n=t.inputRef("IntWhereInputArgument").implement({fields:e=>({eq:e.int(),ne:e.int(),gt:e.int(),gte:e.int(),lt:e.int(),lte:e.int(),in:e.intList(),notIn:e.intList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.intList(),arrayContained:e.intList(),arrayContains:e.intList(),AND:e.field({type:[n]}),OR:e.field({type:[n]}),NOT:e.field({type:n})})}),r=t.inputRef("FloatWhereInputArgument").implement({fields:e=>({eq:e.float(),ne:e.float(),gt:e.float(),gte:e.float(),lt:e.float(),lte:e.float(),in:e.floatList(),notIn:e.floatList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.floatList(),arrayContained:e.floatList(),arrayContains:e.floatList(),AND:e.field({type:[r]}),OR:e.field({type:[r]}),NOT:e.field({type:r})})}),p=t.inputRef("StringWhereInputArgument").implement({fields:e=>({eq:e.string(),ne:e.string(),gt:e.string(),gte:e.string(),lt:e.string(),lte:e.string(),in:e.stringList(),notIn:e.stringList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.stringList(),arrayContained:e.stringList(),arrayContains:e.stringList(),AND:e.field({type:[p]}),OR:e.field({type:[p]}),NOT:e.field({type:p})})}),i=t.inputRef("DateWhereInputArgument").implement({fields:e=>({eq:e.field({type:"Date"}),ne:e.field({type:"Date"}),gt:e.field({type:"Date"}),gte:e.field({type:"Date"}),lt:e.field({type:"Date"}),lte:e.field({type:"Date"}),in:e.field({type:["Date"]}),notIn:e.field({type:["Date"]}),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.field({type:["Date"]}),arrayContained:e.field({type:["Date"]}),arrayContains:e.field({type:["Date"]}),AND:e.field({type:[i]}),OR:e.field({type:[i]}),NOT:e.field({type:i})})});}var ge=({db:t,disableDefaultObjects:n,pubsub:r,pothosConfig:p})=>{let i=new we({...p,plugins:[ye,Ke,_e,...p?.plugins??[]],drizzle:{client:t,relations:t._.relations,getTableConfig(e){return {columns:Object.values(e[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(e[Symbol.for("drizzle:Columns")]).filter(c=>c.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((e,c)=>r.subscribe(e))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),fe(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var Xe=t=>{t.actions||(t.actions=["read","update","delete"]),t.defaultLimit===void 0&&(t.defaultLimit=100);let n=re(t),r=ie({...t,abilityBuilder:n}),{makePubSubInstance:p,pubsub:i}=pe({...t}),{schemaBuilder:e}=ge({...t,pubsub:i}),c=oe({...t,schemaBuilder:e}),l=de({...t,schemaBuilder:e,enumImplementer:c}),u=le({...t,schemaBuilder:e}),y=ae({...t,schemaBuilder:e,makePubSubInstance:p,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:c,abilityBuilder:n}),s=me({...t,schemaBuilder:e,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:p}),d=v(()=>e.toSchema());return {abilityBuilder:n,schemaBuilder:e,createYoga:o=>createYoga({...o,schema:d(),context:r}),createSofa:o=>(o.openAPI&&(o.openAPI={...se,...o.openAPI}),useSofa({...o,schema:d(),context:r})),object:y,whereArg:l,orderArg:u,query:s,pubsub:p,enum_:c}};export{I as RumbleError,k as RumbleErrorSafe,V as assertFindFirstExists,Ce as assertFirstEntryExists,De as mapNullFieldsToUndefined,Xe as rumble};//# sourceMappingURL=index.js.map
9
9
  //# sourceMappingURL=index.js.map