@m1212e/rumble 0.11.7 → 0.12.3

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/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
package/README.md DELETED
@@ -1,285 +0,0 @@
1
- # rumble
2
- rumble is a combined ability and graphql builder built around [drizzle](https://orm.drizzle.team/docs/overview) and [pothos](https://pothos-graphql.dev/docs/plugins/drizzle), inspired by [CASL](https://casl.js.org/v6/en/). It takes much of the required configuration off your shoulders and makes creating a GraphQL (or event REST via [SOFA](https://the-guild.dev/graphql/sofa-api)) api very easy! Additionally it offers strong support for real time data via GraphQL subscriptions!
3
-
4
- > Please note that drizzle hasn't reached a full stable release yet and, as shown in the warning [here](https://pothos-graphql.dev/docs/plugins/drizzle), this is not stable yet.
5
-
6
- > Using rumble and reading these docs requires some basic knowledge about the above mentioned tools. If you feel stuck, please make sure to familiarize yourself with those first! Especially familiarity with pothos and its drizzle plugin are very helpful!
7
-
8
- ## Getting started
9
- The following example is an excerpt from the example setup you can find [here](./example). If you are interested in a real world app thats using rumble (and is still work in progress) please see [CHASE](https://github.com/DeutscheModelUnitedNations/munify-chase).
10
-
11
- First, install rumble into your project:
12
- ```
13
- bun add @m1212e/rumble
14
- npm i @m1212e/rumble
15
- ```
16
- then call the rumble creator:
17
- ```ts
18
- import * as schema from "./db/schema";
19
- import { rumble } from "@m1212e/rumble";
20
-
21
- export const db = drizzle(
22
- "postgres://postgres:postgres@localhost:5432/postgres",
23
- { schema }
24
- );
25
-
26
- const { abilityBuilder } = rumble({ db });
27
- ```
28
- > If the creation of a drizzle instance with the schema definition seems unfamiliar to you, please see their excellent [getting started guide](https://orm.drizzle.team/docs/get-started)
29
-
30
- The rumble creator returns some functions which you can use to implement your api. The concepts rumble uses are described in the following sections:
31
-
32
- ## Abilities
33
- Abilities are the way you define who can do things in your app. You can imagine an ability as `a thing that is allowed`. Abilities can be very wide and applied in general or precisely and narrowly scoped to very specific conditions. You can create abilities with the `abilityBuilder` function returned from the rumble initiator. There are three kinds of abilities:
34
-
35
- ### Wildcard
36
- Wildcard abilities allow everyone to do a thing. The `allow` call takes a single `action` or an array of `action` strings. You can customize the available actions when calling the rumble initializer.
37
- ```ts
38
- // everyone can read posts
39
- abilityBuilder.posts.allow("read");
40
-
41
- // everyone can read and write posts
42
- abilityBuilder.posts.allow(["read", "write"]);
43
- ```
44
-
45
- ### Condition Object
46
- Condition object abilities allow a thing under a certain, fixed condition which does not change. __Note, that the object has the same type as a drizzle query call.__
47
- ```ts
48
- // everyone can read published posts
49
- abilityBuilder.posts.allow("read").when({
50
- where: { published: true },
51
- });
52
- ```
53
-
54
- ### Condition Function
55
- Condition functions are functions that return condition objects. They are called each time an evaluation takes place and can dynamically decide if something should be allowed or not. They receive the request context as a parameter to decide e.g. based on cookies or headers if something is allowed or not.
56
- ```ts
57
- // only the author can update posts
58
- abilityBuilder.posts
59
- .allow(["update", "delete"])
60
- .when(({ userId }) => ({ where: { authorId: userId } }));
61
-
62
- ```
63
-
64
- ### Application level filters
65
- In some cases you can't implement all your checks via a database query filter. Say, for example, you want to query an external api which handles your authorization, before you return the data to the user. This can be done with application layer filters. They can be set very similar to abilities:
66
- ```ts
67
- abilityBuilder.users.filter("read").by(({ context, entities }) => {
68
- // const allowed = await queryExternalAuthorizationService(context.user, entities);
69
-
70
- // we could filter the list to only return the entities the user is allowed to see
71
- // event mapping to prevent leakage of certain fields is possible
72
- return entities;
73
- });
74
- ```
75
- The default implementation helpers automatically respect and call the filters, if you set any. Filters work in addition to abilities. They run on the completed query, which in most cases has had an ability applied, hence abilities have higher priority than filters. If you need to apply a filter to a manually implemented object, please use the `applyFilters` config field as shown in the example project.
76
-
77
-
78
- ### Applying abilities
79
- As you might have noticed, abilities resolve around drizzle query filters. This means, that we can use them to query the database with filters applied that directly restrict what the user is allowed to see, update and retrieve.
80
- ```ts
81
- schemaBuilder.queryFields((t) => {
82
- return {
83
- posts: t.drizzleField({
84
- type: [PostRef],
85
- resolve: (query, root, args, ctx, info) => {
86
- return db.query.posts.findMany(
87
- // here we apply our filter
88
- query(ctx.abilities.posts.filter("read").query.many),
89
- );
90
- },
91
- }),
92
- };
93
- });
94
- ```
95
-
96
- > The `filter()` call returns an object with `query` and `sql` fields. Depending on if you are using the drizzle query or and SQL based API (like update or delete), you need to apply different filters. Same goes for the `query.many` and `query.single` fields.
97
-
98
- #### Applying filters
99
- Applying filters on objects is done automatically if you use the helpers. If you manually implement an object ref, you can use the `applyFilters` config field to ensure the filters run as expected:
100
- ```ts
101
- const PostRef = schemaBuilder.drizzleObject("posts", {
102
- name: "Post",
103
- // apply the application level filters
104
- applyFilters: abilityBuilder.registeredFilters.posts.read,
105
- fields: (t) => ({
106
- ...
107
- ```
108
- To apply filters in a custom handler implementation, like e.g. your mutations, you can use the `applyFilters` helper exported by rumble to easily filter a list of entities.
109
-
110
- ## Context & Configuration
111
- The `rumble` initiator offers various configuration options which you can pass. Most importantly, the `context` provider function which creates the request context that is passed to your abilities and resolvers.
112
- ```ts
113
- rumble({
114
- db,
115
- context(request) {
116
- return {
117
- // here you could instead read some cookies or HTTP headers to retrieve an actual userId
118
- userId: 2,
119
- };
120
- },
121
- });
122
- ```
123
- > `rumble` offers more config options, use intellisense or take a look at [the rumble input type](lib/types/rumbleInput.ts) if you want to know more.
124
-
125
- ## Helpers
126
- Rumble offers various helpers to make it easy and fast to implement your api. Ofcourse you can write your api by hand using the provided `schemaBuilder` from the rumble initiator, but since this might get repetitive, the provided helpers automate a lot of this work for you while also automatically applying the concepts of rumble directly into your api.
127
-
128
- ### arg
129
- `arg` is a helper to implement query arguments for filtering the results of a query for certain results. In many cases you would implement arguments for a query with something as `matchUsername: t.arg.string()` which is supposed to restrict the query to users which have that username. The arg helper implements such a filter tailored to the specific entity which you then can directly pass on to the database query.
130
- ```ts
131
- const WhereArgs = arg({
132
- table: "posts",
133
- });
134
-
135
- schemaBuilder.queryFields((t) => {
136
- return {
137
- postsFiltered: t.drizzleField({
138
- type: [PostRef],
139
- args: {
140
- // here we set our generated type as type for the where argument
141
- where: t.arg({ type: WhereArgs }),
142
- },
143
- resolve: (query, root, args, ctx, info) => {
144
- return db.query.posts.findMany(
145
- query(
146
- // here we apply the ability filter
147
- ctx.abilities.users.filter("read", {
148
- // we can inject one time filters into the permission filter
149
- inject: {
150
- where: args.where,
151
- },
152
- }).query.many,
153
- ),
154
- );
155
- },
156
- }),
157
- };
158
- });
159
- ```
160
-
161
- ### object
162
- `object` is a helper to implement an object with relations. Don't worry about abilities, they are automatically applied. The helper returns the object reference which you can use in the rest of your api, for an example on how to use a type, see the above code snippet (`type: [PostRef],`).
163
- ```ts
164
- const UserRef = object({
165
- table: "users",
166
- });
167
- ```
168
-
169
- ### query
170
- The `query` helper is even simpler. It implements a `findFirst` and `findMany` query for the specified entity named as singular and plural of the entities name.
171
- ```ts
172
- query({
173
- table: "users",
174
- });
175
-
176
- ```
177
-
178
- ### pubsub
179
- In case you want to use subscriptions, `rumble` has got you covered! The rumble helpers all use the `smart subscriptions plugin` from `pothos`. The `pubsub` helper lets you easily hook into the subscription notification logic.
180
- ```ts
181
- const { updated, created, removed } = pubsub({
182
- table: "users",
183
- });
184
- ```
185
- Now just call the functions whenever your application does the respective action and your subscriptions will get notified:
186
- ```ts
187
- updateUsernameHandler() => {
188
- await db.updateTheUsername();
189
- // the pubsub function
190
- updated(user.id);
191
- }
192
- // or if creating
193
- createUserHandler() => {
194
- await db.createTheUser();
195
- // the pubsub function
196
- created();
197
- }
198
- ```
199
- All `query` and `object` helper implementations will automatically update and work right out of the box, no additional config needed!
200
-
201
- > The rumble initiator lets you configure the subscription notifiers in case you want to use an external service like redis for your pubsub notifications instead of the internal default one
202
-
203
- ### enum_
204
- The `enum_` helper is a little different to the others, as it will get called internally automatically if another helpers like `object` or `arg` detects an enum field. In most cases you should be good without calling it manually but in case you would like to have a reference to an enum object, you can get it from this helper.
205
- ```ts
206
- const enumRef = enum_({
207
- tsName: "moodEnum",
208
- });
209
- ```
210
- > The enum parameter allows other fields to be used to reference an enum. This is largely due to how this is used internally. Because of the way how drizzle handles enums, we are not able to provide type safety with enums. In case you actually need to use it, the above way is the recommended approach.
211
-
212
- ## Running the server
213
- In case you directly want to run a server from your rumble instance, you can do so by using the `createYoga` function. It returns a graphql `yoga` instance which can be used to provide a graphql api in [a multitude of ways](https://the-guild.dev/graphql/yoga-server/docs/integrations/z-other-environments).
214
- ```ts
215
- import { createServer } from "node:http";
216
- const server = createServer(createYoga());
217
- server.listen(3000, () => {
218
- console.info("Visit http://localhost:3000/graphql");
219
- });
220
-
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
- ```
274
- ### Alternative
275
- As an alternative to use the client generator with a fully instanciated rumble instance, you can also import the `generateFromSchema` function from rumble and pass it a standard `GraphQLSchema` object to generate the client:
276
- ```ts
277
- import { generateFromSchema } from "@m1212e/rumble";
278
-
279
- await generateFromSchema({
280
- // a schema object: https://github.com/graphql/graphql-js/blob/60ae6c48b9c78332bf3d6036e7d931a3617d0674/src/type/schema.ts#L130
281
- schema: yourGraphQLSchemaObject
282
- outputPath: "./generated";
283
- })
284
- ```
285
- This might become handy in separate code bases for api and client.
package/index.cjs DELETED
@@ -1,65 +0,0 @@
1
- 'use strict';var promises=require('fs/promises'),path=require('path'),graphql=require('graphql'),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'),ie=require('pluralize'),mysqlCore=require('drizzle-orm/mysql-core'),sqliteCore=require('drizzle-orm/sqlite-core'),Kt=require('@pothos/core'),Zt=require('@pothos/plugin-drizzle'),en=require('@pothos/plugin-smart-subscriptions'),graphqlScalars=require('graphql-scalars');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ie__default=/*#__PURE__*/_interopDefault(ie);var Kt__default=/*#__PURE__*/_interopDefault(Kt);var Zt__default=/*#__PURE__*/_interopDefault(Zt);var en__default=/*#__PURE__*/_interopDefault(en);function fe({apiUrl:e,rumbleImportPath:n,useExternalUrqlClient:r,availableSubscriptions:i}){let o=[],t="";return typeof r=="string"?o.push(`import { urqlClient } from "${r}";`):(o.push("import { Client, fetchExchange } from '@urql/core';"),o.push("import { cacheExchange } from '@urql/exchange-graphcache';")),o.push(`import { makeLiveQuery, makeMutation, makeSubscription, makeQuery } from '${n}';`),r||(t+=`
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
- `),t+=`
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([${i.values().toArray().map(l=>`"${l}"`).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:t}}function Te(e){if(e instanceof graphql.GraphQLObjectType)return nt(e);if(e instanceof graphql.GraphQLScalarType)return at(e);if(e instanceof graphql.GraphQLEnumType)return lt(e);if(e instanceof graphql.GraphQLInputObjectType)return rt(e);throw new Error(`Unknown model type: ${e}`)}function nt(e){let n=new Map;for(let[r,i]of Object.entries(e.getFields()))n.set(r,it(i.type,i.args));return `{
42
- ${n.entries().map(([r,i])=>`${r}: ${i}`).toArray().join(`,
43
- `)}
44
- }`}function rt(e){let n=new Map;for(let[r,i]of Object.entries(e.getFields()))n.set(r,ot(i.type));return `{
45
- ${n.entries().map(([r,i])=>`${r}${i.includes("| undefined")?"?":""}: ${i}`).toArray().join(`,
46
- `)}
47
- }`}function it(e,n){let r=false,i=false;for(let a=0;a<3;a++)e instanceof graphql.GraphQLList&&(i=true,e=e.ofType),e instanceof graphql.GraphQLNonNull&&(r=true,e=e.ofType);let o=e.name;i&&(o+="[]"),r||(o+=" | null");let t=e instanceof graphql.GraphQLObjectType,l=new Map;for(let a of n??[])l.set(a.name,st(a.type));if(t){let a=l.entries().every(([,m])=>m.includes("| undefined"));return `(${(n??[]).length>0?`p${a?"?":""}: {
48
- ${l.entries().map(([m,u])=>` ${m}${u.includes("| undefined")?"?":""}: ${u}`).toArray().join(`,
49
- `)}
50
- }`:""}) => ${o}`}else return o}function ot(e){let n=false,r=false;for(let o=0;o<3;o++)e instanceof graphql.GraphQLList&&(r=true,e=e.ofType),e instanceof graphql.GraphQLNonNull&&(n=true,e=e.ofType);let i=e.name;return r&&(i+="[]"),n?r&&(i+=" | undefined"):i+=" | null | undefined",i}function st(e){let n="unknown",r=true;return e instanceof graphql.GraphQLNonNull&&(r=false,e=e.ofType),(e instanceof graphql.GraphQLInputObjectType||e instanceof graphql.GraphQLScalarType)&&(n=e.name),r&&(n+=" | null | undefined"),n}function at(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 lt(e){return e.getValues().map(n=>`"${n.name}"`).join(" | ")}async function se({outputPath:e,schema:n,rumbleImportPath:r="@m1212e/rumble",apiUrl:i,useExternalUrqlClient:o=false}){try{await promises.access(e),await promises.rm(e,{recursive:!0,force:!0});}catch{}await promises.mkdir(e,{recursive:true}),e.endsWith("/")||(e+="/");let t=[],l="",a=new Map;for(let[m,u]of Object.entries(n.getTypeMap()))m.startsWith("__")||a.set(m,u);for(let[m,u]of a.entries()){let d=Te(u);d!==m&&(l+=`
51
- export type ${m} = ${d};
52
- `);}let s=fe({apiUrl:i,useExternalUrqlClient:o,rumbleImportPath:r,availableSubscriptions:new Set(Object.keys(n.getSubscriptionType()?.getFields()||{}))});t.push(...s.imports),l+=s.code,await promises.writeFile(path.join(e,"client.ts"),`${t.join(`
53
- `)}
54
- ${l}`);}var O="__args";function W({queryName:e,input:n,client:r,enableSubscription:i=false}){let o=`${esToolkit.capitalize(e)}Query`,t=_(n[O]??{}),l=u=>`${u} ${o} { ${e}${t} { ${U(n)} }}`,a,s=wonka.pipe(wonka.merge([r.query(l("query"),{}),i?r.subscription(l("subscription"),{}):wonka.empty]),wonka.map(u=>{let d=u.data?.[e];if(!d&&u.error)throw u.error;return d}),wonka.onPush(u=>{a&&Object.assign(a,u);})),m=new Promise(u=>{let d=wonka.toObservable(s).subscribe(p=>{d();let D=wonka.pipe(wonka.merge([s,wonka.fromValue(p)]),wonka.toObservable);a={...p,...D},u(a);}).unsubscribe;});return Object.assign(m,wonka.toObservable(s)),m}function Se({mutationName:e,input:n,client:r}){let i=`${esToolkit.capitalize(e)}Mutation`,o=_(n[O]??{}),t=wonka.pipe(r.mutation(`mutation ${i} { ${e}${o} { ${U(n)} }}`,{}),wonka.map(s=>{let m=s.data?.[e];if(!m&&s.error)throw s.error;return m})),l=wonka.toObservable(t),a=wonka.toPromise(t).then(s=>(Object.assign(s,l),s));return Object.assign(a,l),a}function De({subscriptionName:e,input:n,client:r}){let i=`${esToolkit.capitalize(e)}Subscription`,o=_(n[O]??{});return wonka.pipe(r.subscription(`subscription ${i} { ${e}${o} { ${U(n)} }}`,{}),wonka.map(t=>{let l=t.data?.[e];if(!l&&t.error)throw t.error;return l}),wonka.toObservable)}function U(e){return Object.entries(e).filter(([n])=>n!==O).reduce((n,[r,i])=>{if(typeof i=="object"){if(i[O]){let o=_(i[O]);return n+=`${r}${o} { ${U(i)} }
55
- `,n}n+=`${r} { ${U(i)} }
56
- `;}else n+=`${r}
57
- `;return n},"")}function _(e){let n=Object.entries(e);return n.length===0?"":`(${n.map(([r,i])=>`${r}: ${Ce(i)}`).join(", ")})`}function Ce(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(([n,r])=>`${n}: ${Ce(r)}`).join(", ")} }`;case "function":throw new Error("Cannot stringify a function to send as gql arg")}}function ht({urqlClient:e,availableSubscriptions:n}){return new Proxy({},{get:(r,i)=>o=>W({queryName:i,input:o,client:e,enableSubscription:n.has(i)})})}function Tt({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>Se({mutationName:r,input:i,client:e})})}function xt({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>W({queryName:r,input:i,client:e,enableSubscription:false})})}function St({urqlClient:e}){return new Proxy({},{get:(n,r)=>i=>De({subscriptionName:r,input:i,client:e})})}var A=class extends Error{constructor(n){super(n),this.name="RumbleError";}},F=class extends graphql.GraphQLError{};var ue=e=>{if(!e)throw new F("Value not found but required (findFirst)");return e},Ct=e=>{let n=e.at(0);if(!n)throw new F("Value not found but required (firstEntry)");return n},Re=async({filters:e,entities:n,context:r})=>Array.from((await Promise.all(e.map(i=>i({context:r,entities:n})))).reduce((i,o)=>(o.forEach(t=>i.add(t)),i),new Set));function Rt(e){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r===null?void 0:r]))}function Q(e){let n,r=false;return ()=>(r||(n=e(),r=true),n)}var Ae=["serial","int","integer","tinyint","smallint","mediumint"];function M(e){return Ae.includes(e)}var Ie=["real","decimal","double","float","numeric"];function K(e){return Ie.includes(e)}var Be=["string","text","varchar","char","text(256)"];function V(e){return Be.includes(e)}var Ne=["uuid"];function J(e){return Ne.includes(e)}var Ee=["boolean"];function H(e){return Ee.includes(e)}var Pe=["timestamp","datetime"];function X(e){return Pe.includes(e)}var Le=["date"];function Y(e){return Le.includes(e)}var Qe=["json"];function Z(e){return Qe.includes(e)}var ee=(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 we(e){if(M(e))return {value1:1,value2:2};if(K(e))return {value1:1.1,value2:2.2};if(V(e))return {value1:"a",value2:"b"};if(J(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(H(e))return {value1:true,value2:false};if(X(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(Y(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(Z(e))return {value1:{a:1},value2:{b:2}};throw ee(e,"Distinct")}var pe=Symbol.for("drizzle:Name"),ke=Symbol.for("drizzle:Columns");function E({dbName:e,tsName:n,table:r,db:i}){let o=r;if(n&&(o=i._.relations.schema[n]),e&&(o=Object.values(i._.relations.schema).find(t=>t[pe]===e)),!o)throw new A(`Could not find schema for ${JSON.stringify({tsName:n,dbName:e,table:r?.[pe]}).toString()}`);return {tableSchema:o,columns:o[ke],get primaryColumns(){return Object.entries(o[ke]).filter(([,t])=>t.primary).reduce((t,[l,a])=>(t[l]=a,t),{})},relations:i._.relations.config[n],dbName:o[pe],get tsName(){return Object.entries(i._.relations.schema).find(([,t])=>t===o).at(0)}}}function Bt(e){return typeof e!="function"}function Nt(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var Et=esToolkit.debounce((e,n)=>{console.warn(`
58
- Warning! No abilities have been registered for
59
-
60
- ${e}/${n}
61
-
62
- but has been accessed. This will block everything. If this is intended, you can ignore this warning. If not, please ensure that you register the ability in your ability builder.
63
- `);},1e3),qe=({db:e,actions:n,defaultLimit:r})=>{let i={},o={},t={},l=a=>{for(let s of n)t[a]||(t[a]={}),t[a][s]||(t[a][s]=[]);return {allow:s=>{let m=o[a];m||(m={},o[a]=m);let u=Array.isArray(s)?s:[s];for(let d of u){let p=m[d];p||(p="unspecified",m[d]=p);}return {when:d=>{for(let p of u)m[p]==="unspecified"&&(m[p]=[]),m[p].push(d);}}},filter:s=>{let m=Array.isArray(s)?s:[s];return {by:u=>{for(let d of m)t[a][d].push(u);}}}}};for(let a of Object.keys(e.query))i[a]=l(a);return {...i,z_registeredQueryFilters:o,z_registeredFilters:t,z_buildWithUserContext:a=>{let s={},m=u=>({filter:(d,p)=>{let D=c=>{let x=Q(()=>{if(!(!c?.where&&!p?.inject?.where)){if(p?.inject?.where&&c?.where)return {AND:[c?.where,p?.inject?.where]};if(p?.inject?.where&&!c?.where)return p?.inject?.where;if(!p?.inject?.where&&c?.where)return c?.where;!p?.inject?.where&&c?.where;}}),C=Q(()=>{let P=x();if(!P)return;let G=E({tsName:u,db:e});return drizzleOrm.relationsFilterToSQL(G.tableSchema,P)}),q=Q(()=>{let P=c?.limit??r;return p?.inject?.limit&&(!P||P>p.inject.limit)&&(P=p.inject.limit),P??void 0}),z=Q(()=>{if(!(!c?.columns&&!p?.inject?.columns))return {...c?.columns,...p?.inject?.columns}}),k={query:{single:{get where(){return x()},columns:z()},many:{get where(){return x()},columns:z(),get limit(){return q()}}},sql:{get where(){return C()}}};return z()||(delete k.query.many.columns,delete k.query.single.columns),k},h=()=>{let c=E({db:e,tsName:u});if(Object.keys(c.primaryColumns).length===0)throw new A(`No primary key found for entity ${u.toString()}`);let x=Object.values(c.primaryColumns)[0],C=we(x.getSQLType());return {where:{AND:[{[x.name]:C.value1},{[x.name]:C.value2}]}}},y=o?.[u]?.[d];if(y==="unspecified")return D();y||(Et(u.toString(),d),y=[h()]);let b=y.filter(Bt),R=y.filter(Nt).map(c=>c(a)),g=R.some(c=>c==="allow"),T=[...b,...R].filter(c=>c!==void 0).filter(c=>c!=="allow");!g&&T.length===0&&(T=[h()]);let L;for(let c of T)c?.limit&&(L===void 0||c.limit>L)&&(L=c.limit);let I;for(let c of [...T,p?.inject])c?.columns&&(I===void 0?I=c.columns:I={...I,...c.columns});let S=g?[]:T.filter(c=>c?.where).map(c=>c.where),f=S.length>0?{OR:S}:void 0;return D({where:f,columns:I,limit:L})},runtimeFilters:d=>t[u][d]});for(let u of Object.keys(e.query))s[u]=m(u);return s}}};var ze=({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:r,outputPath:i,rumbleImportPath:o,useExternalUrqlClient:t})=>{let l=e();await se({schema:l,outputPath:i,rumbleImportPath:o,apiUrl:r,useExternalUrqlClient:t});});var Oe=({context:e,abilityBuilder:n})=>async r=>{let i=e?await e(r):{};return {...i,abilities:n.z_buildWithUserContext(i)}};function te(e){return e instanceof pgCore.PgEnumColumn}var Fe=({db:e,schemaBuilder:n})=>{let r=new Map;return ({tsName:o,enumColumn:t,refName:l})=>{let a,s;if(o){let p=e._.relations.schema[o];a=o.toString();let D=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===p);if(!D)throw new A(`Could not find applied enum column for ${o.toString()}.
64
- Please ensure that you use the enum at least once as a column of a table!`);s=D.enumValues;}else if(t){let p=Object.entries(e._.relations.schema).find(([,D])=>D===t.config.enum);if(!p)throw new A(`Could not find enum in schema for ${t.name}!`);a=p[0],s=t.enumValues;}if(!a||!s)throw new A("Could not determine enum structure!");let m=l??`${esToolkit.capitalize(casing.toCamelCase(a))}Enum`,u=r.get(m);return u||(u=n.enumType(m,{values:s}),r.set(m,u),u)}};var ve={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 ne({sqlType:e,fieldName:n}){let r;if(M(e)&&(r="Int"),K(e)&&(r="Float"),V(e)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),J(e)&&(r="ID"),H(e)&&(r="Boolean"),X(e)&&(r="DateTime"),Y(e)&&(r="Date"),Z(e)&&(r="JSON"),r!==void 0)return r;throw ee(e,"SQL to GQL")}function zt(e){let n=new Set;for(let i of Object.values(e))typeof i=="object"&&(i instanceof pgCore.PgTable?n.add("postgres"):i instanceof mysqlCore.MySqlTable?n.add("mysql"):i 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 je(e){return zt(e._.relations.schema)==="postgres"}async function Ge(e){if(!je(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 re({search:e,args:n,tableSchema:r,abilities:i}){if(e?.enabled&&n.search&&n.search.length>0){let o=esToolkit.cloneDeep(n.orderBy);n.orderBy=l=>{let a=drizzleOrm.sql.join(Object.entries(o??{}).map(([d,p])=>{if(p==="asc")return drizzleOrm.sql`${l[d]} ASC`;if(p==="desc")return drizzleOrm.sql`${l[d]} DESC`;throw new Error(`Invalid value ${p} for orderBy`)}),drizzleOrm.sql.raw(", ")),s=i.query.many.columns?Object.entries(r.columns).filter(([d])=>i.query.many.columns[d]):Object.entries(r.columns),m=drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(s.map(([d])=>drizzleOrm.sql`similarity(${l[d]}::TEXT, ${n.search})`),drizzleOrm.sql.raw(", "))}) DESC`;return o?drizzleOrm.sql.join([a,m],drizzleOrm.sql.raw(", ")):m};let t=esToolkit.cloneDeep(n.where);n.where={AND:[t??{},{RAW:l=>drizzleOrm.sql`GREATEST(${drizzleOrm.sql.join(Object.entries(r.columns).map(([a])=>drizzleOrm.sql`similarity(${l[a]}::TEXT, ${n.search})`),drizzleOrm.sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var vt=e=>typeof e!="object"?false:!!Object.keys(e).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),We=({db:e,search:n,schemaBuilder:r,makePubSubInstance:i,whereArgImplementer:o,orderArgImplementer:t,enumImplementer:l,abilityBuilder:a})=>({table:s,refName:m,readAction:u="read",adjust:d})=>{let p=E({db:e,tsName:s});Object.keys(p.primaryColumns).length===0&&console.warn(`Could not find primary key for ${s.toString()}. Cannot register subscriptions!`);let D=Object.values(p.primaryColumns)[0],{registerOnInstance:h}=i({table:s});return r.drizzleObject(s,{name:m??esToolkit.capitalize(s.toString()),subscribe:(y,b,R)=>{if(!D)return;let g=b[D.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:y,action:"updated",primaryKeyValue:g});},applyFilters:a?.z_registeredFilters?.[s]?.[u],fields:y=>{let b=p.columns,R=(S,f,c)=>{let x=ne({sqlType:S,fieldName:f});switch(x){case "Int":return y.exposeInt(f,{nullable:c});case "String":return y.exposeString(f,{nullable:c});case "Boolean":return y.exposeBoolean(f,{nullable:c});case "Date":return y.field({type:"Date",resolve:C=>C[f],nullable:c});case "DateTime":return y.field({type:"DateTime",resolve:C=>C[f],nullable:c});case "Float":return y.exposeFloat(f,{nullable:c});case "ID":return y.exposeID(f,{nullable:c});case "JSON":return y.field({type:"JSON",resolve:C=>C[f],nullable:c});default:throw new A(`Unsupported object type ${x} for column ${f}`)}},g=new Map,T=d?.(new Proxy(y,{get:(S,f)=>typeof S[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")?S[f]:(...c)=>{let x=S[f](...c),C=c.find(vt);if(!C)throw new A("Expected config object to be passed to adjust field");return g.set(x,{params:c,creatorFunction:S[f],configObject:C}),x}}))??{},L=Object.entries(b).reduce((S,[f,c])=>{if(T[f]){let{params:x,creatorFunction:C,configObject:q}=g.get(T[f]);return typeof q.nullable!="boolean"&&(q.nullable=!c.notNull),T[f]=C.bind(y)(...x),S}if(te(c)){let x=l({enumColumn:c});S[f]=y.field({type:x,resolve:C=>C[f],nullable:!c.notNull});}else S[f]=R(c.getSQLType(),f,!c.notNull);return S},{}),I=Object.entries(p.relations??{}).reduce((S,[f,c])=>{let x=E({db:e,table:c.targetTable}),C=o({dbName:x.dbName}),q=t({dbName:x.dbName}),z=i({table:x.tsName}),k=false,P=true,G="many";c instanceof drizzleOrm.One&&(P=false,k=c.optional,G="single");let ce=(N,v)=>{z.registerOnInstance({instance:N,action:"created"}),z.registerOnInstance({instance:N,action:"removed"});};if(T[f]){let{params:N,creatorFunction:v,configObject:w}=g.get(T[f]);return typeof w.nullable!="boolean"&&(w.nullable=k),typeof w.subscribe!="function"&&(w.subscribe=ce),T[f]=v.bind(y)(...N),S}let ye={where:y.arg({type:C,required:false}),orderBy:y.arg({type:q,required:false}),...P?{offset:y.arg.int({required:false}),limit:y.arg.int({required:false})}:{},search:y.arg.string({required:false})};return (!n?.enabled||!P)&&delete ye.search,S[f]=y.relation(f,{args:ye,subscribe:ce,nullable:k,description:`Get the ${ie__default.default.plural(x.tsName)} related to this ${ie__default.default.singular(p.tsName)}`,query:(N,v)=>{N=JSON.parse(JSON.stringify(N)),P&&re({search:n,args:N,tableSchema:x,abilities:v.abilities[x.tsName].filter(u)});let w=v.abilities[x.tsName].filter(u,{inject:{where:N.where,limit:N.limit}}).query[G];return N.offset&&(w.offset=N.offset),N.orderBy&&(w.orderBy=N.orderBy),w}}),S},{});return {...L,...I,...T}}})};var Gt=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}OrderInputArgument`,_e=({db:e,schemaBuilder:n})=>{let r=new Map,i=Q(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),o=({table:t,refName:l,dbName:a})=>{let s=E({db:e,dbName:a,tsName:t}),m=l??Gt(s.tsName),u=r.get(m);return u||(u=n.inputType(m,{fields:p=>{let D=Object.entries(s.columns).reduce((y,[b])=>(y[b]=p.field({type:i(),required:false}),y),{}),h=Object.entries(s.relations??{}).reduce((y,[b,R])=>{let g=E({db:e,table:R.targetTable}),T=o({dbName:g.dbName});return y[b]=p.field({type:T,required:false}),y},{});return {...D,...h}}}),r.set(m,u),u)};return o};var $t="RUMBLE_SUBSCRIPTION_NOTIFICATION",Wt="REMOVED",_t="UPDATED",Mt="CREATED",Ke=({subscriptions:e})=>{let n=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:n,makePubSubInstance:({table:i})=>{function o({action:t,tableName:l,primaryKeyValue:a}){let s;switch(t){case "created":s=Mt;break;case "removed":s=Wt;break;case "updated":s=_t;break;default:throw new Error(`Unknown action: ${t}`)}return `${$t}/${l}${a?`/${a}`:""}/${s}`}return {registerOnInstance({instance:t,action:l,primaryKeyValue:a}){let s=o({tableName:i.toString(),action:l,primaryKeyValue:a});t.register(s);},created(){let t=o({tableName:i.toString(),action:"created"});return n.publish(t)},removed(){let t=o({tableName:i.toString(),action:"removed"});return n.publish(t)},updated(t){let a=(Array.isArray(t)?t:[t]).map(m=>o({tableName:i.toString(),action:"updated",primaryKeyValue:m})),s=Array.from(new Set(a));for(let m of s)n.publish(m);}}}}};var Ve=({db:e,schemaBuilder:n,search:r,whereArgImplementer:i,orderArgImplementer:o,makePubSubInstance:t})=>({table:l,readAction:a="read",listAction:s="read"})=>{let m=i({table:l}),u=o({table:l}),d=E({db:e,tsName:l}),p=Object.values(d.primaryColumns)[0],{registerOnInstance:D}=t({table:l});return n.queryFields(h=>{let y={where:h.arg({type:m,required:false}),orderBy:h.arg({type:u,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false}),search:h.arg.string({required:false})};return r?.enabled||delete y.search,{[ie__default.default.plural(l.toString())]:h.drizzleField({type:[l],nullable:false,smartSubscription:true,description:`List all ${ie__default.default.plural(l.toString())}`,subscribe:(b,R,g,T,L)=>{D({instance:b,action:"created"}),D({instance:b,action:"removed"});},args:y,resolve:(b,R,g,T,L)=>{g=JSON.parse(JSON.stringify(g)),re({search:r,args:g,tableSchema:d,abilities:T.abilities[l].filter(s)});let I=T.abilities[l].filter(s,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 S=b(I);return I.columns&&(S.columns=I.columns),e.query[l].findMany(S)}}),[ie__default.default.singular(l.toString())]:h.drizzleField({type:l,nullable:false,smartSubscription:true,description:`Get a single ${ie__default.default.singular(l.toString())} by ID`,args:{id:h.arg.id({required:true})},resolve:(b,R,g,T,L)=>{g=JSON.parse(JSON.stringify(g));let I=T.abilities[l].filter(a,{inject:{where:{[p.name]:g.id}}}).query.single,S=b(I);return I.columns&&(S.columns=I.columns),e.query[l].findFirst(S).then(ue)}})}})};var He="ManualFiltersPlugin",Xe=He,Je="applyFilters",me=class extends Kt.BasePlugin{wrapResolve(n,r){return async(i,o,t,l)=>{let a,s=r?.type;if(s.kind==="List"?a=s.type?.ref.currentConfig.pothosOptions[Je]:s.kind==="Object"&&(a=s.ref.currentConfig.pothosOptions[Je]),!a||!Array.isArray(a)||a.length===0)return n(i,o,t,l);let m=await n(i,o,t,l),u=Array.isArray(m)?m:[m],d=Array.isArray(a)?a:[a],p=await Re({filters:d,entities:u,context:t});return Array.isArray(m)?p:p[0]??null}}};Kt__default.default.registerPlugin(He,me);var Xt=e=>`${esToolkit.capitalize(casing.toCamelCase(e.toString()))}WhereInputArgument`,Ye=({db:e,schemaBuilder:n,enumImplementer:r})=>{let i=new Map,o=({table:t,refName:l,dbName:a})=>{let s=E({db:e,dbName:a,tsName:t}),m=l??Xt(s.tsName),u=i.get(m);return u||(u=n.inputType(m,{fields:p=>{let D=(b,R)=>{let g=ne({sqlType:b,fieldName:R});switch(g){case "Int":return p.field({type:"IntWhereInputArgument"});case "String":return p.field({type:"StringWhereInputArgument"});case "Boolean":return p.boolean({required:false});case "Date":return p.field({type:"DateWhereInputArgument"});case "DateTime":return p.field({type:"DateWhereInputArgument"});case "Float":return p.field({type:"FloatWhereInputArgument"});case "ID":return p.id({required:false});case "JSON":return p.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${g} for column ${b}`)}},h=Object.entries(s.columns).reduce((b,[R,g])=>{if(te(g)){let T=r({enumColumn:g});b[R]=p.field({type:T,required:false});}else b[R]=D(g.getSQLType(),R);return b},{}),y=Object.entries(s.relations??{}).reduce((b,[R,g])=>{let T=E({db:e,table:g.targetTable}),L=o({dbName:T.dbName});return b[R]=p.field({type:L,required:false}),b},{});return {...h,...y}}}),i.set(m,u),u)};return o};function Ze(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})})}),i=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:[i]}),OR:t.field({type:[i]}),NOT:t.field({type:i})})}),o=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:[o]}),OR:t.field({type:[o]}),NOT:t.field({type:o})})});}var et=({db:e,disableDefaultObjects:n,pubsub:r,pothosConfig:i})=>{let o=new Kt__default.default({...i,plugins:[Xe,Zt__default.default,en__default.default,...i?.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(l=>l.primary)}}},smartSubscriptions:{...en.subscribeOptionsFromIterator((t,l)=>r.subscribe(t))}});return o.addScalarType("JSON",graphqlScalars.JSONResolver),o.addScalarType("Date",graphqlScalars.DateResolver),o.addScalarType("DateTime",graphqlScalars.DateTimeISOResolver),Ze(o),n?.query||o.queryType({}),n?.subscription||o.subscriptionType({}),n?.mutation||o.mutationType({}),{schemaBuilder:o}};var mn=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&Ge(e.db);let n=qe(e),r=Oe({...e,abilityBuilder:n}),{makePubSubInstance:i,pubsub:o}=Ke({...e}),{schemaBuilder:t}=et({...e,pubsub:o}),l=Fe({...e,schemaBuilder:t}),a=Ye({...e,schemaBuilder:t,enumImplementer:l}),s=_e({...e,schemaBuilder:t}),m=We({...e,schemaBuilder:t,makePubSubInstance:i,whereArgImplementer:a,orderArgImplementer:s,enumImplementer:l,abilityBuilder:n}),u=Ve({...e,schemaBuilder:t,whereArgImplementer:a,orderArgImplementer:s,makePubSubInstance:i}),d=Q(()=>t.toSchema()),p=y=>{let b=y?.enableApiDocs??process?.env?.NODE_ENV==="development";return graphqlYoga.createYoga({...y,graphiql:b,plugins:[...y?.plugins??[],...b?[]:[pluginDisableIntrospection.useDisableIntrospection(),graphqlArmor.EnvelopArmorPlugin()]].filter(Boolean),schema:d(),context:r})},D=y=>(y.openAPI&&esToolkit.merge(y.openAPI,ve),sofaApi.useSofa({...y,schema:d(),context:r})),h=ze({...e,builtSchema:d});return {abilityBuilder:n,schemaBuilder:t,createYoga:p,createSofa:D,object:m,whereArg:a,orderArg:s,query:u,pubsub:i,enum_:l,clientCreator:h}};exports.RumbleError=A;exports.RumbleErrorSafe=F;exports.assertFindFirstExists=ue;exports.assertFirstEntryExists=Ct;exports.generateFromSchema=se;exports.makeLiveQuery=ht;exports.makeMutation=Tt;exports.makeQuery=xt;exports.makeSubscription=St;exports.mapNullFieldsToUndefined=Rt;exports.rumble=mn;//# sourceMappingURL=index.cjs.map
65
- //# sourceMappingURL=index.cjs.map