@baeta/extension-complexity 0.0.2 → 0.0.4
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/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +139 -0
- package/package.json +15 -10
- package/dist/index.cjs +0 -330
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -62
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @baeta/extension-complexity
|
|
2
2
|
|
|
3
|
+
## 0.0.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [`b59db50`](https://github.com/andreisergiu98/baeta/commit/b59db501a83275ab2d964933080e688a3a5d8820) Thanks [@andreisergiu98](https://github.com/andreisergiu98)! - add readme
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`b59db50`](https://github.com/andreisergiu98/baeta/commit/b59db501a83275ab2d964933080e688a3a5d8820)]:
|
|
10
|
+
- @baeta/core@0.1.5
|
|
11
|
+
- @baeta/errors@0.1.4
|
|
12
|
+
|
|
13
|
+
## 0.0.3
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- [#180](https://github.com/andreisergiu98/baeta/pull/180) [`483c709`](https://github.com/andreisergiu98/baeta/commit/483c70932f815fd114732c00b74f9488d7924c72) Thanks [@andreisergiu98](https://github.com/andreisergiu98)! - Raise minimum required NodeJS version to 22.12.0. Drop CommonJS builds in favor of the require_esm feature from NodeJS 22.12.0 onwards.
|
|
18
|
+
|
|
19
|
+
- [`de6e89c`](https://github.com/andreisergiu98/baeta/commit/de6e89c1b592e280967c73a4137d24ee56ef1857) Thanks [@andreisergiu98](https://github.com/andreisergiu98)! - raise es target to 2024
|
|
20
|
+
|
|
21
|
+
- Updated dependencies [[`483c709`](https://github.com/andreisergiu98/baeta/commit/483c70932f815fd114732c00b74f9488d7924c72), [`de6e89c`](https://github.com/andreisergiu98/baeta/commit/de6e89c1b592e280967c73a4137d24ee56ef1857)]:
|
|
22
|
+
- @baeta/core@0.1.4
|
|
23
|
+
- @baeta/errors@0.1.3
|
|
24
|
+
|
|
3
25
|
## 0.0.2
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Pampu Andrei
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/andreisergiu98/baeta/refs/heads/main/website/static/img/logo-baeta.svg" alt="Baeta Logo" width="150"/>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<div align="center">
|
|
6
|
+
<h1>Baeta</h1>
|
|
7
|
+
<a href="https://www.npmjs.com/package/@baeta/cli"><img src="https://img.shields.io/npm/v/@baeta/cli.svg?style=flat" /></a>
|
|
8
|
+
<a href="https://github.com/andreisergiu98/baeta/actions/workflows/testing.yml"><img src="https://img.shields.io/github/actions/workflow/status/andreisergiu98/baeta/testing.yml" /></a>
|
|
9
|
+
<a href="https://github.com/andreisergiu98/baeta/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" /></a>
|
|
10
|
+
<a href="https://github.com/andreisergiu98/baeta/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" /></a>
|
|
11
|
+
<br />
|
|
12
|
+
<br />
|
|
13
|
+
<a href="https://baeta.io/docs/getting-started/installation">Getting Started</a>
|
|
14
|
+
<span> • </span>
|
|
15
|
+
<a href="https://www.baeta.io/">Website</a>
|
|
16
|
+
<span> • </span>
|
|
17
|
+
<a href="https://baeta.io/docs/intro">Docs</a>
|
|
18
|
+
<span> • </span>
|
|
19
|
+
<a href="https://github.com/andreisergiu98/baeta/tree/main/examples">Examples</a>
|
|
20
|
+
<span> • </span>
|
|
21
|
+
<a href="https://discord.gg/BHFXHvyj">Discord</a>
|
|
22
|
+
<br />
|
|
23
|
+
<hr />
|
|
24
|
+
</div>
|
|
25
|
+
|
|
26
|
+
# What is Baeta?
|
|
27
|
+
|
|
28
|
+
Building GraphQL APIs shouldn't be complicated. **Baeta** is a modern, modular, open-source GraphQL framework designed with flexibility in mind. It follows a granular approach where you only add what you need, helping developers focus on what matters most - creating powerful, scalable APIs without the boilerplate.
|
|
29
|
+
|
|
30
|
+
### Key Features
|
|
31
|
+
|
|
32
|
+
- **Modular Architecture**: Organize your API into manageable modules
|
|
33
|
+
- **Schema-First Development**: Define your API contract upfront
|
|
34
|
+
- **Type Safety**: Automatic code generation for type-safe development
|
|
35
|
+
- **Middleware & Directives**: Easy integration of custom behaviors
|
|
36
|
+
- **High Performance**: Built for scalability and efficiency
|
|
37
|
+
|
|
38
|
+
#### And optional extensions and plugins
|
|
39
|
+
|
|
40
|
+
- **@baeta/extension-auth**: Add powerful scope-based authorization
|
|
41
|
+
- **@baeta/extension-cache**: Implement automatic caching with simple update patterns
|
|
42
|
+
- ... and more!
|
|
43
|
+
|
|
44
|
+
## Why use Baeta?
|
|
45
|
+
|
|
46
|
+
Baeta makes it easy to build better GraphQL APIs while staying flexible. Here's how:
|
|
47
|
+
|
|
48
|
+
**Granular and Progressive:** Start small and add features as you need them. Whether you're building a simple API or a complex system, Baeta scales with your needs.
|
|
49
|
+
|
|
50
|
+
**Modular architecture:** Baeta's modular design allows you to organize your GraphQL API into smaller, more manageable modules that can be added or removed as needed. This makes it easier to maintain and scale your API over time.
|
|
51
|
+
|
|
52
|
+
**Schema-first approach:** With Baeta, you define your schema first, and then logic and resolvers. This approach ensures a consistent and well-defined API for your clients and reduces boilerplate code.
|
|
53
|
+
|
|
54
|
+
## How it Works
|
|
55
|
+
|
|
56
|
+
#### 1. Define your schema
|
|
57
|
+
|
|
58
|
+
```graphql
|
|
59
|
+
type User {
|
|
60
|
+
id: ID!
|
|
61
|
+
name: String!
|
|
62
|
+
email: String!
|
|
63
|
+
age: Int
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
input UserWhereUnique {
|
|
67
|
+
id: ID
|
|
68
|
+
email: String
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type Query {
|
|
72
|
+
user(where: UserWhereUnique!): User!
|
|
73
|
+
users: [User!]!
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### 2. Implement your resolvers
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { getUserModule } from "./typedef";
|
|
81
|
+
|
|
82
|
+
const { Query } = getUserModule();
|
|
83
|
+
|
|
84
|
+
Query.user(({ args }) => {
|
|
85
|
+
return dataSource.user.find(args.where);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
Query.users(() => {
|
|
89
|
+
return dataSource.user.findMany();
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### 3. Add authorization
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
const { Query, Mutation } = getUserModule();
|
|
97
|
+
|
|
98
|
+
Query.users.$auth({
|
|
99
|
+
$or: {
|
|
100
|
+
isPublic: true,
|
|
101
|
+
isLoggedIn: true,
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
#### 4. Add caching
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import { getUserModule } from "./typedef";
|
|
110
|
+
|
|
111
|
+
const { User, Query } = getUserModule();
|
|
112
|
+
|
|
113
|
+
export const userCache = User.$createCache();
|
|
114
|
+
|
|
115
|
+
Query.user.$useCache(userCache);
|
|
116
|
+
Query.users.$useCache(userCache);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Compatibility
|
|
120
|
+
|
|
121
|
+
Baeta is compatible with all GraphQL servers, which makes it easy to integrate with your existing stack. It works seamlessly with popular GraphQL server libraries such as **Graphql Yoga** and **Apollo Server**, as well as other popular tools like **Prisma**, **Drizzle** and **Kysely**.
|
|
122
|
+
|
|
123
|
+
Baeta's development tools are built for Node.js, but the runtime code is environment-agnostic. This means your Baeta applications can run anywhere JavaScript runs, including:
|
|
124
|
+
|
|
125
|
+
- Deno
|
|
126
|
+
- Cloudflare Workers
|
|
127
|
+
- AWS Lambda
|
|
128
|
+
- Vercel Edge Functions
|
|
129
|
+
- Bun
|
|
130
|
+
- Node.js
|
|
131
|
+
- Any other JavaScript runtime
|
|
132
|
+
|
|
133
|
+
## Credits
|
|
134
|
+
|
|
135
|
+
Baeta was inspired by several amazing projects and people in the GraphQL ecosystem. Check out our [Credits page](https://baeta.io/docs/credits) to learn more about the individuals and projects that influenced Baeta's development.
|
|
136
|
+
|
|
137
|
+
## License
|
|
138
|
+
|
|
139
|
+
Baeta is licensed under the [MIT License](./LICENSE).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baeta/extension-complexity",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"baeta",
|
|
6
6
|
"graphql",
|
|
@@ -28,8 +28,7 @@
|
|
|
28
28
|
"exports": {
|
|
29
29
|
".": {
|
|
30
30
|
"types": "./dist/index.d.ts",
|
|
31
|
-
"
|
|
32
|
-
"require": "./dist/index.cjs"
|
|
31
|
+
"default": "./dist/index.js"
|
|
33
32
|
}
|
|
34
33
|
},
|
|
35
34
|
"types": "dist/index.d.ts",
|
|
@@ -45,25 +44,24 @@
|
|
|
45
44
|
},
|
|
46
45
|
"devDependencies": {
|
|
47
46
|
"@baeta/builder": "^0.0.0",
|
|
48
|
-
"@baeta/core": "^0.1.
|
|
47
|
+
"@baeta/core": "^0.1.5",
|
|
49
48
|
"@baeta/tsconfig": "^0.0.0",
|
|
50
49
|
"graphql": "^16.9.0",
|
|
51
|
-
"typescript": "^5.
|
|
50
|
+
"typescript": "^5.7.2"
|
|
52
51
|
},
|
|
53
52
|
"peerDependencies": {
|
|
54
|
-
"@baeta/core": "^0.1.
|
|
53
|
+
"@baeta/core": "^0.1.5",
|
|
55
54
|
"graphql": "^16.6.0"
|
|
56
55
|
},
|
|
57
56
|
"engines": {
|
|
58
|
-
"node": ">=22.
|
|
57
|
+
"node": ">=22.12.0"
|
|
59
58
|
},
|
|
60
59
|
"publishConfig": {
|
|
61
60
|
"access": "public",
|
|
62
61
|
"exports": {
|
|
63
62
|
".": {
|
|
64
63
|
"types": "./dist/index.d.ts",
|
|
65
|
-
"
|
|
66
|
-
"require": "./dist/index.cjs"
|
|
64
|
+
"default": "./dist/index.js"
|
|
67
65
|
}
|
|
68
66
|
}
|
|
69
67
|
},
|
|
@@ -77,6 +75,13 @@
|
|
|
77
75
|
]
|
|
78
76
|
},
|
|
79
77
|
"dependencies": {
|
|
80
|
-
"@baeta/errors": "^0.1.
|
|
78
|
+
"@baeta/errors": "^0.1.4"
|
|
79
|
+
},
|
|
80
|
+
"typedocOptions": {
|
|
81
|
+
"entryPoints": [
|
|
82
|
+
"./index.ts"
|
|
83
|
+
],
|
|
84
|
+
"readme": "none",
|
|
85
|
+
"tsconfig": "./tsconfig.json"
|
|
81
86
|
}
|
|
82
87
|
}
|
package/dist/index.cjs
DELETED
|
@@ -1,330 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// lib/complexity-extension.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var _sdk = require('@baeta/core/sdk');
|
|
5
|
-
|
|
6
|
-
// lib/complexity-calculator.ts
|
|
7
|
-
var _errors = require('@baeta/errors');
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
var _graphql = require('graphql');
|
|
15
|
-
|
|
16
|
-
// utils/graphlq.ts
|
|
17
|
-
|
|
18
|
-
function isListOrNullableList(type) {
|
|
19
|
-
if (type instanceof _graphql.GraphQLList) {
|
|
20
|
-
return true;
|
|
21
|
-
}
|
|
22
|
-
if (type instanceof _graphql.GraphQLNonNull) {
|
|
23
|
-
return isListOrNullableList(type.ofType);
|
|
24
|
-
}
|
|
25
|
-
return false;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// utils/string.ts
|
|
29
|
-
function capitalize(str) {
|
|
30
|
-
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// lib/field-settings.ts
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
function getFieldComplexitySettings(ctx, info, type, field, selection, fieldName, fieldSettingsMap) {
|
|
38
|
-
const args = _graphql.getArgumentValues.call(void 0, field, selection, info.variableValues);
|
|
39
|
-
const customComplexity = _optionalChain([fieldSettingsMap, 'access', _ => _[type.name], 'optionalAccess', _2 => _2[fieldName]]);
|
|
40
|
-
if (customComplexity) {
|
|
41
|
-
return customComplexity({ args, ctx });
|
|
42
|
-
}
|
|
43
|
-
const wildCardComplexity = _optionalChain([fieldSettingsMap, 'access', _3 => _3[type.name], 'optionalAccess', _4 => _4["*"]]);
|
|
44
|
-
if (wildCardComplexity) {
|
|
45
|
-
return wildCardComplexity({ args, ctx });
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
function registerFieldSettingsSetter(type, field, fn, map) {
|
|
49
|
-
map[type] ??= {};
|
|
50
|
-
map[type][field] = fn;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// lib/complexity-calculator.ts
|
|
54
|
-
function calculateComplexity(ctx, info, fieldSettingsMap, defaults) {
|
|
55
|
-
const operationName = capitalize(info.operation.operation);
|
|
56
|
-
const operationType = info.schema.getType(operationName);
|
|
57
|
-
if (!operationType || !_graphql.isOutputType.call(void 0, operationType)) {
|
|
58
|
-
throw new (0, _errors.ValidationError)(`Unsupported operation ${operationName}`);
|
|
59
|
-
}
|
|
60
|
-
return complexityFromSelectionSet(
|
|
61
|
-
ctx,
|
|
62
|
-
info,
|
|
63
|
-
operationType,
|
|
64
|
-
info.operation.selectionSet,
|
|
65
|
-
fieldSettingsMap,
|
|
66
|
-
defaults
|
|
67
|
-
);
|
|
68
|
-
}
|
|
69
|
-
function complexityFromSelectionSet(ctx, info, type, selectionSet, fieldSettingsMap, defaults) {
|
|
70
|
-
const result = {
|
|
71
|
-
depth: 0,
|
|
72
|
-
breadth: 0,
|
|
73
|
-
complexity: 0
|
|
74
|
-
};
|
|
75
|
-
for (const selection of selectionSet.selections) {
|
|
76
|
-
const selectionResult = complexityFromSelection(
|
|
77
|
-
ctx,
|
|
78
|
-
info,
|
|
79
|
-
type,
|
|
80
|
-
selection,
|
|
81
|
-
fieldSettingsMap,
|
|
82
|
-
defaults
|
|
83
|
-
);
|
|
84
|
-
result.complexity += selectionResult.complexity;
|
|
85
|
-
result.breadth += selectionResult.breadth;
|
|
86
|
-
result.depth = Math.max(result.depth, selectionResult.depth);
|
|
87
|
-
}
|
|
88
|
-
return result;
|
|
89
|
-
}
|
|
90
|
-
function complexityFromSelection(ctx, info, type, selection, fieldSettingsMap, defaults) {
|
|
91
|
-
if (selection.kind === _graphql.Kind.FIELD) {
|
|
92
|
-
return complexityFromField(ctx, info, type, selection, fieldSettingsMap, defaults);
|
|
93
|
-
}
|
|
94
|
-
if (selection.kind === _graphql.Kind.FRAGMENT_SPREAD) {
|
|
95
|
-
const fragment = info.fragments[selection.name.value];
|
|
96
|
-
if (!fragment) {
|
|
97
|
-
throw new (0, _errors.ValidationError)(`Fragment ${selection.name.value} not found`);
|
|
98
|
-
}
|
|
99
|
-
return complexityFromFragment(ctx, info, type, fragment, fieldSettingsMap, defaults);
|
|
100
|
-
}
|
|
101
|
-
return complexityFromFragment(ctx, info, type, selection, fieldSettingsMap, defaults);
|
|
102
|
-
}
|
|
103
|
-
function complexityFromFragment(ctx, info, type, fragment, fieldSettingsMap, defaults) {
|
|
104
|
-
const fragmentType = fragment.typeCondition ? info.schema.getType(fragment.typeCondition.name.value) : type;
|
|
105
|
-
if (!_graphql.isOutputType.call(void 0, fragmentType)) {
|
|
106
|
-
throw new (0, _errors.ValidationError)(`Unsupported fragment type ${fragmentType}`);
|
|
107
|
-
}
|
|
108
|
-
if (!fragmentType) {
|
|
109
|
-
throw new (0, _errors.ValidationError)(`Fragment type ${fragmentType} not found`);
|
|
110
|
-
}
|
|
111
|
-
return complexityFromSelectionSet(
|
|
112
|
-
ctx,
|
|
113
|
-
info,
|
|
114
|
-
fragmentType,
|
|
115
|
-
fragment.selectionSet,
|
|
116
|
-
fieldSettingsMap,
|
|
117
|
-
defaults
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
function complexityFromField(ctx, info, type, selection, fieldSettingsMap, defaults) {
|
|
121
|
-
const fieldName = selection.name.value;
|
|
122
|
-
const field = _graphql.isObjectType.call(void 0, type) || _graphql.isInterfaceType.call(void 0, type) ? type.getFields()[fieldName] : void 0;
|
|
123
|
-
if (!field && !fieldName.startsWith("__")) {
|
|
124
|
-
throw new (0, _errors.ValidationError)(`Field ${fieldName} not found on type ${type.name}`);
|
|
125
|
-
}
|
|
126
|
-
if (!field) {
|
|
127
|
-
return {
|
|
128
|
-
depth: 1,
|
|
129
|
-
breadth: 1,
|
|
130
|
-
complexity: 1
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
const fieldComplexitySettings = getFieldComplexitySettings(
|
|
134
|
-
ctx,
|
|
135
|
-
info,
|
|
136
|
-
type,
|
|
137
|
-
field,
|
|
138
|
-
selection,
|
|
139
|
-
fieldName,
|
|
140
|
-
fieldSettingsMap
|
|
141
|
-
);
|
|
142
|
-
if (fieldComplexitySettings === false) {
|
|
143
|
-
return {
|
|
144
|
-
depth: 0,
|
|
145
|
-
breadth: 0,
|
|
146
|
-
complexity: 0
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
let depth = 1;
|
|
150
|
-
let breadth = 1;
|
|
151
|
-
let complexity = 0;
|
|
152
|
-
const listMultiplier = _nullishCoalesce(_optionalChain([fieldComplexitySettings, 'optionalAccess', _5 => _5.multiplier]), () => ( defaults.multiplier));
|
|
153
|
-
const multiplier = field && isListOrNullableList(field.type) ? listMultiplier : 1;
|
|
154
|
-
complexity += (_nullishCoalesce(_optionalChain([fieldComplexitySettings, 'optionalAccess', _6 => _6.complexity]), () => ( defaults.complexity))) * multiplier;
|
|
155
|
-
if (!field || !selection.selectionSet) {
|
|
156
|
-
return {
|
|
157
|
-
depth,
|
|
158
|
-
breadth,
|
|
159
|
-
complexity
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
const subSelection = complexityFromSelectionSet(
|
|
163
|
-
ctx,
|
|
164
|
-
info,
|
|
165
|
-
_graphql.getNamedType.call(void 0, field.type),
|
|
166
|
-
selection.selectionSet,
|
|
167
|
-
fieldSettingsMap,
|
|
168
|
-
defaults
|
|
169
|
-
);
|
|
170
|
-
depth += subSelection.depth;
|
|
171
|
-
breadth += subSelection.breadth;
|
|
172
|
-
complexity += subSelection.complexity * Math.max(multiplier, 1);
|
|
173
|
-
return {
|
|
174
|
-
depth,
|
|
175
|
-
breadth,
|
|
176
|
-
complexity
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// lib/complexity-errors.ts
|
|
181
|
-
|
|
182
|
-
var ComplexityErrorKind = /* @__PURE__ */ ((ComplexityErrorKind2) => {
|
|
183
|
-
ComplexityErrorKind2["Depth"] = "DepthExceeded";
|
|
184
|
-
ComplexityErrorKind2["Breadth"] = "BreadthExceeded";
|
|
185
|
-
ComplexityErrorKind2["Complexity"] = "ComplexityExceeded";
|
|
186
|
-
return ComplexityErrorKind2;
|
|
187
|
-
})(ComplexityErrorKind || {});
|
|
188
|
-
function getDefaultComplexityError(kind, limit, result) {
|
|
189
|
-
if (kind === "DepthExceeded" /* Depth */) {
|
|
190
|
-
return new (0, _errors.ValidationError)(`Depth limit of ${limit} exceeded, got: ${result}`);
|
|
191
|
-
}
|
|
192
|
-
if (kind === "BreadthExceeded" /* Breadth */) {
|
|
193
|
-
return new (0, _errors.ValidationError)(`Breadth limit of ${limit} exceeded, got: ${result}`);
|
|
194
|
-
}
|
|
195
|
-
if (kind === "ComplexityExceeded" /* Complexity */) {
|
|
196
|
-
return new (0, _errors.ValidationError)(`Complexity limit of ${limit} exceeded, got: ${result}`);
|
|
197
|
-
}
|
|
198
|
-
throw new Error("Unknown complexity error kind");
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// lib/complexity-options.ts
|
|
202
|
-
var defaultLimits = {
|
|
203
|
-
depth: 10,
|
|
204
|
-
breadth: 50,
|
|
205
|
-
complexity: 1e3
|
|
206
|
-
};
|
|
207
|
-
function normalizeOptions(options) {
|
|
208
|
-
return {
|
|
209
|
-
limit: _nullishCoalesce(options.limit, () => ( defaultLimits)),
|
|
210
|
-
defaultComplexity: _nullishCoalesce(options.defaultComplexity, () => ( 1)),
|
|
211
|
-
defaultListMultiplier: _nullishCoalesce(options.defaultListMultiplier, () => ( 10)),
|
|
212
|
-
complexityError: _nullishCoalesce(options.complexityError, () => ( getDefaultComplexityError))
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// lib/store.ts
|
|
217
|
-
var _core = require('@baeta/core');
|
|
218
|
-
var complexityStoreKey = Symbol("complexity-extension");
|
|
219
|
-
var [getComplexityStore, setComplexityStoreLoader] = _core.createContextStore.call(void 0, complexityStoreKey);
|
|
220
|
-
|
|
221
|
-
// lib/store-loader.ts
|
|
222
|
-
function loadComplexityStore(ctx, getLimits, defaultLimits2) {
|
|
223
|
-
setComplexityStoreLoader(ctx, async () => {
|
|
224
|
-
const limits = typeof getLimits === "function" ? await getLimits(ctx) : getLimits;
|
|
225
|
-
let cache = void 0;
|
|
226
|
-
const cacheComplexity = (fn) => {
|
|
227
|
-
if (cache) {
|
|
228
|
-
return cache;
|
|
229
|
-
}
|
|
230
|
-
cache = fn();
|
|
231
|
-
return cache;
|
|
232
|
-
};
|
|
233
|
-
return {
|
|
234
|
-
limits: {
|
|
235
|
-
depth: _nullishCoalesce(_optionalChain([limits, 'optionalAccess', _7 => _7.depth]), () => ( defaultLimits2.depth)),
|
|
236
|
-
breadth: _nullishCoalesce(_optionalChain([limits, 'optionalAccess', _8 => _8.breadth]), () => ( defaultLimits2.breadth)),
|
|
237
|
-
complexity: _nullishCoalesce(_optionalChain([limits, 'optionalAccess', _9 => _9.complexity]), () => ( defaultLimits2.complexity))
|
|
238
|
-
},
|
|
239
|
-
cacheComplexity
|
|
240
|
-
};
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// lib/complexity-extension.ts
|
|
245
|
-
var ComplexityExtension = (_class = class extends _sdk.Extension {
|
|
246
|
-
|
|
247
|
-
constructor(options = {}) {
|
|
248
|
-
super();_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);;
|
|
249
|
-
this.options = normalizeOptions(options);
|
|
250
|
-
}
|
|
251
|
-
__init() {this.fieldSettingsMap = {}}
|
|
252
|
-
__init2() {this.getTypeExtensions = (_module, type) => {
|
|
253
|
-
return {
|
|
254
|
-
$complexity: (fn) => {
|
|
255
|
-
registerFieldSettingsSetter(type, "*", fn, this.fieldSettingsMap);
|
|
256
|
-
}
|
|
257
|
-
};
|
|
258
|
-
}}
|
|
259
|
-
__init3() {this.getResolverExtensions = (_module, type, field) => {
|
|
260
|
-
return {
|
|
261
|
-
$complexity: (fn) => {
|
|
262
|
-
registerFieldSettingsSetter(type, field, fn, this.fieldSettingsMap);
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
}}
|
|
266
|
-
__init4() {this.getSubscriptionExtensions = (_module, field) => {
|
|
267
|
-
return {
|
|
268
|
-
$complexity: (fn) => {
|
|
269
|
-
registerFieldSettingsSetter("Subscription", field, fn, this.fieldSettingsMap);
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
}}
|
|
273
|
-
createComplexityMiddleware() {
|
|
274
|
-
return (next) => async (root, args, ctx, info) => {
|
|
275
|
-
loadComplexityStore(ctx, this.options.limit, defaultLimits);
|
|
276
|
-
const store = await getComplexityStore(ctx);
|
|
277
|
-
const limits = store.limits;
|
|
278
|
-
const results = store.cacheComplexity(() => {
|
|
279
|
-
return calculateComplexity(ctx, info, this.fieldSettingsMap, {
|
|
280
|
-
complexity: this.options.defaultComplexity,
|
|
281
|
-
multiplier: this.options.defaultListMultiplier
|
|
282
|
-
});
|
|
283
|
-
});
|
|
284
|
-
if (results.depth > limits.depth) {
|
|
285
|
-
throw this.options.complexityError("DepthExceeded" /* Depth */, limits.depth, results.depth);
|
|
286
|
-
}
|
|
287
|
-
if (results.breadth > limits.breadth) {
|
|
288
|
-
throw this.options.complexityError(
|
|
289
|
-
"BreadthExceeded" /* Breadth */,
|
|
290
|
-
limits.breadth,
|
|
291
|
-
results.breadth
|
|
292
|
-
);
|
|
293
|
-
}
|
|
294
|
-
if (results.complexity > limits.complexity) {
|
|
295
|
-
throw this.options.complexityError(
|
|
296
|
-
"ComplexityExceeded" /* Complexity */,
|
|
297
|
-
limits.complexity,
|
|
298
|
-
results.complexity
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
return next(root, args, ctx, info);
|
|
302
|
-
};
|
|
303
|
-
}
|
|
304
|
-
__init5() {this.build = (_module, mapper) => {
|
|
305
|
-
for (const type of mapper.getTypes()) {
|
|
306
|
-
if (type !== "Query" && type !== "Mutation" && type !== "Subscription") {
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
if (type !== "Subscription") {
|
|
310
|
-
for (const field of mapper.getTypeFields(type)) {
|
|
311
|
-
mapper.prependMiddleware(type, field, this.createComplexityMiddleware());
|
|
312
|
-
}
|
|
313
|
-
continue;
|
|
314
|
-
}
|
|
315
|
-
for (const field of mapper.getTypeFields(type)) {
|
|
316
|
-
mapper.prependMiddleware(type, `${field}.subscribe`, this.createComplexityMiddleware());
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
}}
|
|
320
|
-
}, _class);
|
|
321
|
-
|
|
322
|
-
// index.ts
|
|
323
|
-
function complexityExtension(options) {
|
|
324
|
-
return () => new ComplexityExtension(options);
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
exports.ComplexityErrorKind = ComplexityErrorKind; exports.complexityExtension = complexityExtension;
|
|
330
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/baeta/baeta/packages/extension-complexity/dist/index.cjs","../lib/complexity-extension.ts","../lib/complexity-calculator.ts","../utils/graphlq.ts","../utils/string.ts","../lib/field-settings.ts","../lib/complexity-errors.ts","../lib/complexity-options.ts","../lib/store.ts","../lib/store-loader.ts","../index.ts"],"names":["ComplexityErrorKind"],"mappings":"AAAA;ACAA;AACC;AAAA,sCAIM;ADDP;AACA;AELA,uCAAgC;AAChC;AAMC;AAGA;AACA;AACA;AACA;AAAA,kCACM;AFAP;AACA;AGfA;AAEO,SAAS,oBAAA,CAAqB,IAAA,EAAkC;AACtE,EAAA,GAAA,CAAI,KAAA,WAAgB,oBAAA,EAAa;AAChC,IAAA,OAAO,IAAA;AAAA,EACR;AAEA,EAAA,GAAA,CAAI,KAAA,WAAgB,uBAAA,EAAgB;AACnC,IAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,MAAM,CAAA;AAAA,EACxC;AAEA,EAAA,OAAO,KAAA;AACR;AHcA;AACA;AI3BO,SAAS,UAAA,CAAW,GAAA,EAAa;AACvC,EAAA,OAAO,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,CAAY,EAAA,EAAI,GAAA,CAAI,KAAA,CAAM,CAAC,CAAA;AACjD;AJ6BA;AACA;AKhCA;AAKC;AAAA;AAuBM,SAAS,0BAAA,CACf,GAAA,EACA,IAAA,EACA,IAAA,EACA,KAAA,EACA,SAAA,EACA,SAAA,EACA,gBAAA,EACC;AACD,EAAA,MAAM,KAAA,EAAO,wCAAA,KAAkB,EAAO,SAAA,EAAW,IAAA,CAAK,cAAc,CAAA;AACpE,EAAA,MAAM,iBAAA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D,EAAA;AAE4D,kBAAA;AACrB,IAAA;AACmB,MAAA;AACvD,QAAA;AACD,MAAA;AAE6B,MAAA;AACoB,QAAA;AACJ,UAAA;AAC5C,QAAA;AACA,QAAA;AACD,MAAA;AAEgD,MAAA;AACW,QAAA;AAC3D,MAAA;AACD,IAAA;AACD,EAAA;AACD;ADqMqE;AACA;AUxTe;AACvC,EAAA;AAC7C;AV0TqE;AACA;AACA;AACA","file":"/home/runner/work/baeta/baeta/packages/extension-complexity/dist/index.cjs","sourcesContent":[null,"import {\n\tExtension,\n\ttype ModuleBuilder,\n\ttype NativeMiddleware,\n\ttype ResolverMapper,\n} from '@baeta/core/sdk';\nimport { calculateComplexity } from './complexity-calculator.ts';\nimport { ComplexityErrorKind } from './complexity-errors.ts';\nimport {\n\ttype ComplexityExtensionOptions,\n\tdefaultLimits,\n\tnormalizeOptions,\n} from './complexity-options.ts';\nimport { type FieldSettingsMap, registerFieldSettingsSetter } from './field-settings.ts';\nimport { loadComplexityStore } from './store-loader.ts';\nimport { getComplexityStore } from './store.ts';\n\nexport class ComplexityExtension<Ctx> extends Extension {\n\tprivate readonly options: Required<ComplexityExtensionOptions<Ctx>>;\n\n\tconstructor(options: ComplexityExtensionOptions<Ctx> = {}) {\n\t\tsuper();\n\t\tthis.options = normalizeOptions(options);\n\t}\n\n\tprivate fieldSettingsMap: FieldSettingsMap = {};\n\n\tgetTypeExtensions = <Root, Context>(\n\t\t_module: ModuleBuilder,\n\t\ttype: string,\n\t): BaetaExtensions.TypeExtensions<Root, Context> => {\n\t\treturn {\n\t\t\t$complexity: (fn) => {\n\t\t\t\tregisterFieldSettingsSetter(type, '*', fn, this.fieldSettingsMap);\n\t\t\t},\n\t\t};\n\t};\n\n\tgetResolverExtensions = <Result, Root, Context, Args>(\n\t\t_module: ModuleBuilder,\n\t\ttype: string,\n\t\tfield: string,\n\t): BaetaExtensions.ResolverExtensions<Result, Root, Context, Args> => {\n\t\treturn {\n\t\t\t$complexity: (fn) => {\n\t\t\t\tregisterFieldSettingsSetter(type, field, fn, this.fieldSettingsMap);\n\t\t\t},\n\t\t};\n\t};\n\n\tgetSubscriptionExtensions = <Root, Context, Args>(\n\t\t_module: ModuleBuilder,\n\t\tfield: string,\n\t): BaetaExtensions.SubscriptionExtensions<Root, Context, Args> => {\n\t\treturn {\n\t\t\t$complexity: (fn) => {\n\t\t\t\tregisterFieldSettingsSetter('Subscription', field, fn, this.fieldSettingsMap);\n\t\t\t},\n\t\t};\n\t};\n\n\tcreateComplexityMiddleware<Result, Root, Context, Args>(): NativeMiddleware<\n\t\tResult,\n\t\tRoot,\n\t\tContext,\n\t\tArgs\n\t> {\n\t\treturn (next) => async (root, args, ctx, info) => {\n\t\t\tloadComplexityStore(ctx as unknown as Ctx, this.options.limit, defaultLimits);\n\n\t\t\tconst store = await getComplexityStore(ctx);\n\n\t\t\tconst limits = store.limits;\n\n\t\t\tconst results = store.cacheComplexity(() => {\n\t\t\t\treturn calculateComplexity(ctx as unknown as Ctx, info, this.fieldSettingsMap, {\n\t\t\t\t\tcomplexity: this.options.defaultComplexity,\n\t\t\t\t\tmultiplier: this.options.defaultListMultiplier,\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tif (results.depth > limits.depth) {\n\t\t\t\tthrow this.options.complexityError(ComplexityErrorKind.Depth, limits.depth, results.depth);\n\t\t\t}\n\n\t\t\tif (results.breadth > limits.breadth) {\n\t\t\t\tthrow this.options.complexityError(\n\t\t\t\t\tComplexityErrorKind.Breadth,\n\t\t\t\t\tlimits.breadth,\n\t\t\t\t\tresults.breadth,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (results.complexity > limits.complexity) {\n\t\t\t\tthrow this.options.complexityError(\n\t\t\t\t\tComplexityErrorKind.Complexity,\n\t\t\t\t\tlimits.complexity,\n\t\t\t\t\tresults.complexity,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn next(root, args, ctx, info);\n\t\t};\n\t}\n\n\tbuild = (_module: ModuleBuilder, mapper: ResolverMapper) => {\n\t\tfor (const type of mapper.getTypes()) {\n\t\t\tif (type !== 'Query' && type !== 'Mutation' && type !== 'Subscription') {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (type !== 'Subscription') {\n\t\t\t\tfor (const field of mapper.getTypeFields(type)) {\n\t\t\t\t\tmapper.prependMiddleware(type, field, this.createComplexityMiddleware());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const field of mapper.getTypeFields(type)) {\n\t\t\t\tmapper.prependMiddleware(type, `${field}.subscribe`, this.createComplexityMiddleware());\n\t\t\t}\n\t\t}\n\t};\n}\n","import { ValidationError } from '@baeta/errors';\nimport {\n\ttype FieldNode,\n\ttype FragmentDefinitionNode,\n\ttype GraphQLNamedType,\n\ttype GraphQLResolveInfo,\n\ttype InlineFragmentNode,\n\tKind,\n\ttype SelectionNode,\n\ttype SelectionSetNode,\n\tgetNamedType,\n\tisInterfaceType,\n\tisObjectType,\n\tisOutputType,\n} from 'graphql';\nimport { isListOrNullableList } from '../utils/graphlq.ts';\nimport { capitalize } from '../utils/string.ts';\nimport { type FieldSettingsMap, getFieldComplexitySettings } from './field-settings.ts';\n\ninterface ComplexityDefaults {\n\tcomplexity: number;\n\tmultiplier: number;\n}\n\nexport function calculateComplexity<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\tfieldSettingsMap: FieldSettingsMap,\n\tdefaults: ComplexityDefaults,\n) {\n\tconst operationName = capitalize(info.operation.operation);\n\tconst operationType = info.schema.getType(operationName);\n\n\tif (!operationType || !isOutputType(operationType)) {\n\t\tthrow new ValidationError(`Unsupported operation ${operationName}`);\n\t}\n\n\treturn complexityFromSelectionSet(\n\t\tctx,\n\t\tinfo,\n\t\toperationType,\n\t\tinfo.operation.selectionSet,\n\t\tfieldSettingsMap,\n\t\tdefaults,\n\t);\n}\n\nfunction complexityFromSelectionSet<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\ttype: GraphQLNamedType,\n\tselectionSet: SelectionSetNode,\n\tfieldSettingsMap: FieldSettingsMap,\n\tdefaults: ComplexityDefaults,\n) {\n\tconst result = {\n\t\tdepth: 0,\n\t\tbreadth: 0,\n\t\tcomplexity: 0,\n\t};\n\n\tfor (const selection of selectionSet.selections) {\n\t\tconst selectionResult = complexityFromSelection(\n\t\t\tctx,\n\t\t\tinfo,\n\t\t\ttype,\n\t\t\tselection,\n\t\t\tfieldSettingsMap,\n\t\t\tdefaults,\n\t\t);\n\t\tresult.complexity += selectionResult.complexity;\n\t\tresult.breadth += selectionResult.breadth;\n\t\tresult.depth = Math.max(result.depth, selectionResult.depth);\n\t}\n\n\treturn result;\n}\n\nfunction complexityFromSelection<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\ttype: GraphQLNamedType,\n\tselection: SelectionNode,\n\tfieldSettingsMap: FieldSettingsMap,\n\tdefaults: ComplexityDefaults,\n) {\n\tif (selection.kind === Kind.FIELD) {\n\t\treturn complexityFromField(ctx, info, type, selection, fieldSettingsMap, defaults);\n\t}\n\n\tif (selection.kind === Kind.FRAGMENT_SPREAD) {\n\t\tconst fragment = info.fragments[selection.name.value];\n\n\t\tif (!fragment) {\n\t\t\tthrow new ValidationError(`Fragment ${selection.name.value} not found`);\n\t\t}\n\n\t\treturn complexityFromFragment(ctx, info, type, fragment, fieldSettingsMap, defaults);\n\t}\n\n\treturn complexityFromFragment(ctx, info, type, selection, fieldSettingsMap, defaults);\n}\n\nfunction complexityFromFragment<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\ttype: GraphQLNamedType,\n\tfragment: FragmentDefinitionNode | InlineFragmentNode,\n\tfieldSettingsMap: FieldSettingsMap,\n\tdefaults: ComplexityDefaults,\n) {\n\tconst fragmentType = fragment.typeCondition\n\t\t? info.schema.getType(fragment.typeCondition.name.value)\n\t\t: type;\n\n\tif (!isOutputType(fragmentType)) {\n\t\tthrow new ValidationError(`Unsupported fragment type ${fragmentType}`);\n\t}\n\n\tif (!fragmentType) {\n\t\tthrow new ValidationError(`Fragment type ${fragmentType} not found`);\n\t}\n\n\treturn complexityFromSelectionSet(\n\t\tctx,\n\t\tinfo,\n\t\tfragmentType,\n\t\tfragment.selectionSet,\n\t\tfieldSettingsMap,\n\t\tdefaults,\n\t);\n}\n\nfunction complexityFromField<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\ttype: GraphQLNamedType,\n\tselection: FieldNode,\n\tfieldSettingsMap: FieldSettingsMap,\n\tdefaults: ComplexityDefaults,\n) {\n\tconst fieldName = selection.name.value;\n\n\tconst field =\n\t\tisObjectType(type) || isInterfaceType(type) ? type.getFields()[fieldName] : undefined;\n\n\tif (!field && !fieldName.startsWith('__')) {\n\t\tthrow new ValidationError(`Field ${fieldName} not found on type ${type.name}`);\n\t}\n\n\tif (!field) {\n\t\treturn {\n\t\t\tdepth: 1,\n\t\t\tbreadth: 1,\n\t\t\tcomplexity: 1,\n\t\t};\n\t}\n\n\tconst fieldComplexitySettings = getFieldComplexitySettings(\n\t\tctx,\n\t\tinfo,\n\t\ttype,\n\t\tfield,\n\t\tselection,\n\t\tfieldName,\n\t\tfieldSettingsMap,\n\t);\n\n\tif (fieldComplexitySettings === false) {\n\t\treturn {\n\t\t\tdepth: 0,\n\t\t\tbreadth: 0,\n\t\t\tcomplexity: 0,\n\t\t};\n\t}\n\n\tlet depth = 1;\n\tlet breadth = 1;\n\tlet complexity = 0;\n\n\tconst listMultiplier = fieldComplexitySettings?.multiplier ?? defaults.multiplier;\n\tconst multiplier = field && isListOrNullableList(field.type) ? listMultiplier : 1;\n\n\tcomplexity += (fieldComplexitySettings?.complexity ?? defaults.complexity) * multiplier;\n\n\tif (!field || !selection.selectionSet) {\n\t\treturn {\n\t\t\tdepth,\n\t\t\tbreadth,\n\t\t\tcomplexity,\n\t\t};\n\t}\n\n\tconst subSelection = complexityFromSelectionSet(\n\t\tctx,\n\t\tinfo,\n\t\tgetNamedType(field.type),\n\t\tselection.selectionSet,\n\t\tfieldSettingsMap,\n\t\tdefaults,\n\t);\n\n\tdepth += subSelection.depth;\n\tbreadth += subSelection.breadth;\n\tcomplexity += subSelection.complexity * Math.max(multiplier, 1);\n\n\treturn {\n\t\tdepth,\n\t\tbreadth,\n\t\tcomplexity,\n\t};\n}\n","import { GraphQLList, GraphQLNonNull, type GraphQLOutputType } from 'graphql';\n\nexport function isListOrNullableList(type: GraphQLOutputType): boolean {\n\tif (type instanceof GraphQLList) {\n\t\treturn true;\n\t}\n\n\tif (type instanceof GraphQLNonNull) {\n\t\treturn isListOrNullableList(type.ofType);\n\t}\n\n\treturn false;\n}\n","export function capitalize(str: string) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n","import {\n\ttype FieldNode,\n\ttype GraphQLField,\n\ttype GraphQLNamedType,\n\ttype GraphQLResolveInfo,\n\tgetArgumentValues,\n} from 'graphql';\n\nexport type FieldSettingsMap = Record<\n\tstring,\n\t// biome-ignore lint/suspicious/noExplicitAny: Match any type from the original code\n\tRecord<string, GetFieldSettings<any, any> | undefined> | undefined\n>;\n\nexport type FieldSettings = {\n\tcomplexity?: number;\n\tmultiplier?: number;\n};\n\nexport type GetFieldSettingsArgs<Context, Args> = {\n\targs: Args;\n\tctx: Context;\n};\n\nexport type GetFieldSettings<Context, Args> = (\n\tparams: GetFieldSettingsArgs<Context, Args>,\n) => FieldSettings | false;\n\nexport function getFieldComplexitySettings<Context>(\n\tctx: Context,\n\tinfo: GraphQLResolveInfo,\n\ttype: GraphQLNamedType,\n\tfield: GraphQLField<unknown, unknown>,\n\tselection: FieldNode,\n\tfieldName: string,\n\tfieldSettingsMap: FieldSettingsMap,\n) {\n\tconst args = getArgumentValues(field, selection, info.variableValues);\n\tconst customComplexity = fieldSettingsMap[type.name]?.[fieldName];\n\n\tif (customComplexity) {\n\t\treturn customComplexity({ args, ctx });\n\t}\n\n\tconst wildCardComplexity = fieldSettingsMap[type.name]?.['*'];\n\n\tif (wildCardComplexity) {\n\t\treturn wildCardComplexity({ args, ctx });\n\t}\n}\n\nexport function registerFieldSettingsSetter<Context, Args>(\n\ttype: string,\n\tfield: string,\n\tfn: GetFieldSettings<Context, Args>,\n\tmap: FieldSettingsMap,\n) {\n\tmap[type] ??= {};\n\tmap[type][field] = fn;\n}\n","import { ValidationError } from '@baeta/errors';\nimport type { GraphQLError } from 'graphql';\n\nexport enum ComplexityErrorKind {\n\tDepth = 'DepthExceeded',\n\tBreadth = 'BreadthExceeded',\n\tComplexity = 'ComplexityExceeded',\n}\n\nexport type GetComplexityError = (\n\tkind: ComplexityErrorKind,\n\tlimits: number,\n\tresults: number,\n) => GraphQLError;\n\nexport function getDefaultComplexityError(\n\tkind: ComplexityErrorKind,\n\tlimit: number,\n\tresult: number,\n): GraphQLError {\n\tif (kind === ComplexityErrorKind.Depth) {\n\t\treturn new ValidationError(`Depth limit of ${limit} exceeded, got: ${result}`);\n\t}\n\n\tif (kind === ComplexityErrorKind.Breadth) {\n\t\treturn new ValidationError(`Breadth limit of ${limit} exceeded, got: ${result}`);\n\t}\n\n\tif (kind === ComplexityErrorKind.Complexity) {\n\t\treturn new ValidationError(`Complexity limit of ${limit} exceeded, got: ${result}`);\n\t}\n\n\tthrow new Error('Unknown complexity error kind');\n}\n","import { type GetComplexityError, getDefaultComplexityError } from './complexity-errors.ts';\nimport type { GetComplexityLimit } from './complexity-limits.ts';\n\nexport interface ComplexityExtensionOptions<Context> {\n\tlimit?: GetComplexityLimit<Context>;\n\tdefaultComplexity?: number;\n\tdefaultListMultiplier?: number;\n\tcomplexityError?: GetComplexityError;\n}\n\nexport const defaultLimits = {\n\tdepth: 10,\n\tbreadth: 50,\n\tcomplexity: 1000,\n};\n\nexport type NormalizedOptions<Context> = Required<ComplexityExtensionOptions<Context>>;\n\nexport function normalizeOptions<Context>(\n\toptions: ComplexityExtensionOptions<Context>,\n): NormalizedOptions<Context> {\n\treturn {\n\t\tlimit: options.limit ?? defaultLimits,\n\t\tdefaultComplexity: options.defaultComplexity ?? 1,\n\t\tdefaultListMultiplier: options.defaultListMultiplier ?? 10,\n\t\tcomplexityError: options.complexityError ?? getDefaultComplexityError,\n\t};\n}\n","import { createContextStore } from '@baeta/core';\nimport type { ComplexityLimit } from './complexity-limits.ts';\n\nexport interface ComplexityStore {\n\tlimits: Required<ComplexityLimit>;\n\tcacheComplexity: (fn: () => Required<ComplexityLimit>) => Required<ComplexityLimit>;\n}\n\nexport const complexityStoreKey = Symbol('complexity-extension');\n\nexport const [getComplexityStore, setComplexityStoreLoader] =\n\tcreateContextStore<ComplexityStore>(complexityStoreKey);\n","import type { ComplexityLimit } from './complexity-limits.ts';\nimport { setComplexityStoreLoader } from './store.ts';\n\nexport function loadComplexityStore<T>(\n\tctx: T,\n\tgetLimits: ComplexityLimit | ((ctx: T) => ComplexityLimit | Promise<ComplexityLimit>) | undefined,\n\tdefaultLimits: Required<ComplexityLimit>,\n) {\n\tsetComplexityStoreLoader(ctx, async () => {\n\t\tconst limits = typeof getLimits === 'function' ? await getLimits(ctx) : getLimits;\n\n\t\tlet cache: Required<ComplexityLimit> | undefined = undefined;\n\n\t\tconst cacheComplexity = (fn: () => Required<ComplexityLimit>) => {\n\t\t\tif (cache) {\n\t\t\t\treturn cache;\n\t\t\t}\n\n\t\t\tcache = fn();\n\t\t\treturn cache;\n\t\t};\n\n\t\treturn {\n\t\t\tlimits: {\n\t\t\t\tdepth: limits?.depth ?? defaultLimits.depth,\n\t\t\t\tbreadth: limits?.breadth ?? defaultLimits.breadth,\n\t\t\t\tcomplexity: limits?.complexity ?? defaultLimits.complexity,\n\t\t\t},\n\t\t\tcacheComplexity,\n\t\t};\n\t});\n}\n","import './lib/global-types.ts';\n\nimport { ComplexityExtension } from './lib/complexity-extension.ts';\nimport type { ComplexityExtensionOptions } from './lib/complexity-options.ts';\n\nexport { ComplexityErrorKind, type GetComplexityError } from './lib/complexity-errors.ts';\nexport type { ComplexityLimit, GetComplexityLimit } from './lib/complexity-limits.ts';\nexport type { ComplexityExtensionOptions } from './lib/complexity-options.ts';\n\nexport function complexityExtension<Ctx>(options?: ComplexityExtensionOptions<Ctx>) {\n\treturn () => new ComplexityExtension(options);\n}\n"]}
|
package/dist/index.d.cts
DELETED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { Extension, ModuleBuilder, NativeMiddleware, ResolverMapper } from '@baeta/core/sdk';
|
|
2
|
-
import { GraphQLError } from 'graphql';
|
|
3
|
-
|
|
4
|
-
type FieldSettings = {
|
|
5
|
-
complexity?: number;
|
|
6
|
-
multiplier?: number;
|
|
7
|
-
};
|
|
8
|
-
type GetFieldSettingsArgs<Context, Args> = {
|
|
9
|
-
args: Args;
|
|
10
|
-
ctx: Context;
|
|
11
|
-
};
|
|
12
|
-
type GetFieldSettings<Context, Args> = (params: GetFieldSettingsArgs<Context, Args>) => FieldSettings | false;
|
|
13
|
-
|
|
14
|
-
declare global {
|
|
15
|
-
export namespace BaetaExtensions {
|
|
16
|
-
interface ResolverExtensions<Result, Root, Context, Args> {
|
|
17
|
-
$complexity: (fn: GetFieldSettings<Context, Args>) => void;
|
|
18
|
-
}
|
|
19
|
-
interface TypeExtensions<Root, Context> {
|
|
20
|
-
$complexity: (fn: GetFieldSettings<Context, unknown>) => void;
|
|
21
|
-
}
|
|
22
|
-
interface SubscriptionExtensions<Root, Context, Args> {
|
|
23
|
-
$complexity: (fn: GetFieldSettings<Context, Args>) => void;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
declare enum ComplexityErrorKind {
|
|
29
|
-
Depth = "DepthExceeded",
|
|
30
|
-
Breadth = "BreadthExceeded",
|
|
31
|
-
Complexity = "ComplexityExceeded"
|
|
32
|
-
}
|
|
33
|
-
type GetComplexityError = (kind: ComplexityErrorKind, limits: number, results: number) => GraphQLError;
|
|
34
|
-
|
|
35
|
-
interface ComplexityLimit {
|
|
36
|
-
depth?: number;
|
|
37
|
-
breadth?: number;
|
|
38
|
-
complexity?: number;
|
|
39
|
-
}
|
|
40
|
-
type GetComplexityLimit<Context> = ComplexityLimit | ((ctx: Context) => ComplexityLimit | Promise<ComplexityLimit>);
|
|
41
|
-
|
|
42
|
-
interface ComplexityExtensionOptions<Context> {
|
|
43
|
-
limit?: GetComplexityLimit<Context>;
|
|
44
|
-
defaultComplexity?: number;
|
|
45
|
-
defaultListMultiplier?: number;
|
|
46
|
-
complexityError?: GetComplexityError;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
declare class ComplexityExtension<Ctx> extends Extension {
|
|
50
|
-
private readonly options;
|
|
51
|
-
constructor(options?: ComplexityExtensionOptions<Ctx>);
|
|
52
|
-
private fieldSettingsMap;
|
|
53
|
-
getTypeExtensions: <Root, Context>(_module: ModuleBuilder, type: string) => BaetaExtensions.TypeExtensions<Root, Context>;
|
|
54
|
-
getResolverExtensions: <Result, Root, Context, Args>(_module: ModuleBuilder, type: string, field: string) => BaetaExtensions.ResolverExtensions<Result, Root, Context, Args>;
|
|
55
|
-
getSubscriptionExtensions: <Root, Context, Args>(_module: ModuleBuilder, field: string) => BaetaExtensions.SubscriptionExtensions<Root, Context, Args>;
|
|
56
|
-
createComplexityMiddleware<Result, Root, Context, Args>(): NativeMiddleware<Result, Root, Context, Args>;
|
|
57
|
-
build: (_module: ModuleBuilder, mapper: ResolverMapper) => void;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
declare function complexityExtension<Ctx>(options?: ComplexityExtensionOptions<Ctx>): () => ComplexityExtension<Ctx>;
|
|
61
|
-
|
|
62
|
-
export { ComplexityErrorKind, type ComplexityExtensionOptions, type ComplexityLimit, type GetComplexityError, type GetComplexityLimit, complexityExtension };
|