@graxia/envelop 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Softistx
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 CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @graxia/envelop
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run [Envelop](https://the-guild.dev/graphql/envelop) plugins inside graxia with one import and one call.
4
+
5
+ ```ts
6
+ import { createGraxia } from '@graxia/core';
7
+ import { fromEnvelop } from '@graxia/envelop';
8
+ import { useDepthLimit } from '@envelop/depth-limit';
9
+
10
+ createGraxia({
11
+ schema,
12
+ plugins: [fromEnvelop([useDepthLimit({ maxDepth: 10 })])],
13
+ }).serve();
14
+ ```
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ bun add @graxia/envelop @graxia/core @envelop/core graphql
20
+ bun add @envelop/depth-limit # the Envelop plugins you want
21
+ ```
22
+
23
+ ## Requirements
24
+
25
+ - [Bun](https://bun.sh) 1.4.4 or later (the `engines` field) and `graphql@^17.1`.
26
+ - `@graxia/core` and `@envelop/core` (`^5.6.1 || ^6.0.1`) as peer dependencies. `@envelop/core` is a runtime peer (the adapter imports it).
27
+ - `typescript` is an optional peer, for types. Use `"moduleResolution": "bundler"` in your `tsconfig.json`; `nodenext` is not supported.
28
+
29
+ ## What it runs
30
+
31
+ `fromEnvelop(plugins, { name?, enforce? })` returns one graxia plugin. It honours `onPluginInit`, `onSchemaChange`,
32
+ `onEnveloped`, `onParse`, `onValidate`, `onContextBuilding`, `onExecute` and `onSubscribe`, with their after-hooks and
33
+ `onExecuteDone`, `onSubscribeResult`, `onNext`, `onEnd` and `onSubscribeError`, and `@defer` / `@stream` payloads. Anything
34
+ else (`instrumentation`, a graphql-yoga hook such as `onRequest`, an unknown name, `setSchema`, `replaceSchema`) is refused
35
+ with an error that names what to write instead: at boot, except `setSchema` called in `onEnveloped` (it throws on each
36
+ request) and `replaceSchema` (it fails when `graxia.ready` resolves). Falsy entries are skipped, so `cond && usePlugin()` works.
37
+
38
+ What the plugins add to the context is typed with a type argument, `fromEnvelop<{ currentUser: User }>([...])`; it is a
39
+ declaration, not a check.
40
+
41
+ ## Tested plugins
42
+
43
+ `@envelop/depth-limit`, `@envelop/generic-auth`, `@envelop/response-cache` and `@envelop/persisted-operations` run in this
44
+ package's specs on graphql 17.1, over a real `Bun.serve`. Versions and notes are in the
45
+ [guide](./docs/guide/envelop.md#tested-plugins).
46
+
47
+ ## Documentation
48
+
49
+ See [`docs/`](./docs): the [guide](./docs/guide/envelop.md), [troubleshooting](./docs/troubleshooting.md) and the
50
+ [roadmap](./docs/roadmap.md).
@@ -0,0 +1,13 @@
1
+ import type { GraxiaPlugin } from '@graxia/core';
2
+ import { type opKey } from './early-context.js';
3
+ import type { Adapter } from './types.js';
4
+ type Key = ReturnType<typeof opKey>;
5
+ /**
6
+ * `onParams` (Envelop's `onEnveloped`, once per operation) and `onContext`
7
+ * (`onContextBuilding`, its after-hooks at the end) of the adapter. The
8
+ * context the Envelop hooks build on is `{ request, params, ...the host
9
+ * context }`; what they add is returned and merged into graxia's context.
10
+ */
11
+ export declare function contextHooks(adapter: Adapter, key: Key): Pick<GraxiaPlugin, 'onParams' | 'onContext'>;
12
+ export {};
13
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAoB,MAAM,cAAc,CAAC;AAEnE,OAAO,EAAY,KAAK,KAAK,EAAQ,MAAM,iBAAiB,CAAC;AAE7D,OAAO,KAAK,EAAE,OAAO,EAAS,MAAM,SAAS,CAAC;AAE9C,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC;AAGpC;;;;;GAKG;AACH,wBAAgB,YAAY,CAC3B,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,GAAG,GACN,IAAI,CAAC,YAAY,EAAE,UAAU,GAAG,WAAW,CAAC,CA8B9C"}
@@ -0,0 +1,9 @@
1
+ import type { GraxiaPlugin } from '@graxia/core';
2
+ import { type opKey } from './early-context.js';
3
+ import type { Adapter } from './types.js';
4
+ type Key = ReturnType<typeof opKey>;
5
+ type Hooks = Pick<GraxiaPlugin, 'onParse' | 'onValidate'>;
6
+ /** `onParse` and `onValidate` of the adapter: the Envelop plugins' hooks of the same names, in order. */
7
+ export declare function documentHooks(adapter: Adapter, key: Key): Hooks;
8
+ export {};
9
+ //# sourceMappingURL=document.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,YAAY,EAKZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAY,KAAK,KAAK,EAAQ,MAAM,iBAAiB,CAAC;AAE7D,OAAO,KAAK,EAAE,OAAO,EAAS,MAAM,SAAS,CAAC;AAE9C,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC;AACpC,KAAK,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC;AAG1D,yGAAyG;AACzG,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,GAAG,KAAK,CAW/D"}
@@ -0,0 +1,16 @@
1
+ import { type RequestState } from '@graxia/core';
2
+ import type { Op } from './types.js';
3
+ /** The per-operation record of one adapter (a key per `fromEnvelop` call). */
4
+ export declare const opKey: () => import("@graxia/core").StateKey<Op>;
5
+ /**
6
+ * The Envelop context of this operation, created on first use:
7
+ * `{ request, params }` first, then what the hooks run before `onContext`
8
+ * (`onEnveloped`, `onParse`, `onValidate`) extend it with.
9
+ */
10
+ export declare function opOf(key: ReturnType<typeof opKey>, state: RequestState, seed: {
11
+ request: Request;
12
+ params: unknown;
13
+ }): Op;
14
+ /** `extendContext` of the early hooks: merges into the context and remembers the keys. */
15
+ export declare function extender(op: Op): (extension: object) => void;
16
+ //# sourceMappingURL=early-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"early-context.d.ts","sourceRoot":"","sources":["../src/early-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAElC,8EAA8E;AAC9E,eAAO,MAAM,KAAK,2CAAsC,CAAC;AAEzD;;;;GAIG;AACH,wBAAgB,IAAI,CACnB,GAAG,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,EAC7B,KAAK,EAAE,YAAY,EACnB,IAAI,EAAE;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GACzC,EAAE,CASJ;AAED,0FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAK5D"}
@@ -0,0 +1,8 @@
1
+ import type { GraxiaPlugin } from '@graxia/core';
2
+ import type { opKey } from './early-context.js';
3
+ import type { Adapter } from './types.js';
4
+ type Key = ReturnType<typeof opKey>;
5
+ /** `onExecute` and `onSubscribe` of the adapter, with their done hooks as after-hooks. */
6
+ export declare function executeHooks(adapter: Adapter, key: Key): Pick<GraxiaPlugin, 'onExecute' | 'onSubscribe'>;
7
+ export {};
8
+ //# sourceMappingURL=execute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../src/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,YAAY,EAGZ,MAAM,cAAc,CAAC;AAEtB,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAS7C,OAAO,KAAK,EAAE,OAAO,EAAS,MAAM,SAAS,CAAC;AAE9C,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC;AA4BpC,0FAA0F;AAC1F,wBAAgB,YAAY,CAC3B,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,GAAG,GACN,IAAI,CAAC,YAAY,EAAE,WAAW,GAAG,aAAa,CAAC,CAcjD"}
@@ -0,0 +1,25 @@
1
+ import type { Plugin as EnvelopPlugin } from '@envelop/core';
2
+ import type { Empty, GraxiaPlugin } from '@graxia/core';
3
+ /** Options of {@link fromEnvelop}. */
4
+ export interface FromEnvelopOptions {
5
+ /** The graxia plugin's name (default `envelop`). Two adapters in one instance need distinct names. */
6
+ name?: string;
7
+ /** Where the adapter runs among the other plugins. */
8
+ enforce?: 'pre' | 'post';
9
+ }
10
+ /**
11
+ * Runs Envelop plugins inside graxia as one graxia plugin.
12
+ *
13
+ * Every Envelop hook graxia can honour is mapped onto its own stages; any
14
+ * other hook (`instrumentation`, a graphql-yoga hook, an unknown name) is
15
+ * refused here, at boot, with a `GraxiaConfigError` that says what to write
16
+ * instead. `Added` is what the plugins put in the context (unchecked).
17
+ *
18
+ * @example
19
+ * createGraxia({
20
+ * schema,
21
+ * plugins: [fromEnvelop([useDepthLimit({ maxDepth: 10 })])],
22
+ * }).serve();
23
+ */
24
+ export declare function fromEnvelop<Added extends object = Empty>(plugins: readonly (EnvelopPlugin<any> | false | null | undefined)[], options?: FromEnvelopOptions): GraxiaPlugin<Empty, Added>;
25
+ //# sourceMappingURL=from-envelop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"from-envelop.d.ts","sourceRoot":"","sources":["../src/from-envelop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAQxD,sCAAsC;AACtC,MAAM,WAAW,kBAAkB;IAClC,sGAAsG;IACtG,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,OAAO,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,KAAK,EACvD,OAAO,EAAE,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,KAAK,GAAG,IAAI,GAAG,SAAS,CAAC,EAAE,EACnE,OAAO,GAAE,kBAAuB,GAC9B,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAoB5B"}
@@ -0,0 +1,4 @@
1
+ export type { Plugin as EnvelopPlugin } from '@envelop/core';
2
+ export type { FromEnvelopOptions } from './from-envelop.js';
3
+ export { fromEnvelop } from './from-envelop.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,eAAe,CAAC;AAC7D,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,534 @@
1
+ // src/context.ts
2
+ import { GraphQLError } from "graphql";
3
+
4
+ // src/early-context.ts
5
+ import { createStateKey } from "@graxia/core";
6
+ var opKey = () => createStateKey("envelop");
7
+ function opOf(key, state, seed) {
8
+ const known = state.get(key);
9
+ if (known)
10
+ return known;
11
+ const op = {
12
+ context: { request: seed.request, params: seed.params },
13
+ extended: new Set
14
+ };
15
+ state.set(key, op);
16
+ return op;
17
+ }
18
+ function extender(op) {
19
+ return (extension) => {
20
+ Object.assign(op.context, extension);
21
+ for (const key of Reflect.ownKeys(extension))
22
+ op.extended.add(key);
23
+ };
24
+ }
25
+
26
+ // src/refuse.ts
27
+ import { GraxiaConfigError } from "@graxia/core";
28
+ var SUPPORTED = new Set([
29
+ "onPluginInit",
30
+ "onSchemaChange",
31
+ "onEnveloped",
32
+ "onParse",
33
+ "onValidate",
34
+ "onContextBuilding",
35
+ "onExecute",
36
+ "onSubscribe"
37
+ ]);
38
+ var YOGA_KEYS = new Set([
39
+ "onRequest",
40
+ "onRequestParse",
41
+ "onParams",
42
+ "onResultProcess",
43
+ "onResponse",
44
+ "onYogaInit",
45
+ "onExecutionResult"
46
+ ]);
47
+ var refuse = (message) => new GraxiaConfigError(`fromEnvelop: ${message}`);
48
+ function labelOf(index, total, plugin) {
49
+ const keys = Object.entries(plugin).filter(([, value]) => value !== undefined).map(([key]) => key);
50
+ return `envelop plugin ${index} of ${total} (${keys.join(", ")})`;
51
+ }
52
+ var notAnObject = (index, total, value) => refuse(`entry ${index} of ${total} is ${value === null ? "null" : typeof value}, not an Envelop plugin object. Pass a plugin such as useDepthLimit({ maxDepth: 10 }), or a falsy value (cond && usePlugin()) to skip one.`);
53
+ var instrumentation = (label) => refuse(`${label} uses "instrumentation", which graxia cannot run. Remove it, or use createGraxia({ telemetry }) or a graxia plugin (definePlugin) instead.`);
54
+ var yogaKey = (label, key) => refuse(`${label} uses "${key}": this is a graphql-yoga plugin, not an Envelop one, and graxia cannot run it. Rewrite it with definePlugin from @graxia/core.`);
55
+ var unknownKey = (label, key) => refuse(`${label} uses "${key}", which is not an Envelop hook graxia knows. Check the spelling, or write it as a graxia plugin with definePlugin from @graxia/core.`);
56
+ var setSchema = (label) => refuse(`${label} calls setSchema, which graxia does not honour. Pass the schema to createGraxia({ schema }) instead (useSchema is not needed).`);
57
+ var replaceSchema = (label) => refuse(`${label} calls replaceSchema, which graxia does not honour: an instance serves the one schema it was created with. Pass the schema to createGraxia({ schema }) instead.`);
58
+ var replaceParseResult = (label) => refuse(`${label} calls replaceParseResult, which graxia does not honour. Use setParsedDocument in onParse, or throw a GraphQLError there, instead.`);
59
+ var afterValidateSetResult = (label) => refuse(`${label} calls setResult in the after-hook of onValidate, which graxia does not honour. Call setResult in onValidate itself, or write a graxia plugin (definePlugin) that replaces the errors.`);
60
+
61
+ // src/context.ts
62
+ function contextHooks(adapter, key) {
63
+ const { entries } = adapter;
64
+ const enveloped = entries.filter((e) => e.plugin.onEnveloped);
65
+ const building = entries.filter((e) => e.plugin.onContextBuilding);
66
+ const early = enveloped.length > 0 || building.length > 0 || entries.some((e) => e.plugin.onParse || e.plugin.onValidate || e.plugin.onExecute || e.plugin.onSubscribe);
67
+ if (!early)
68
+ return {};
69
+ return {
70
+ onParams: (payload) => {
71
+ const op = opOf(key, payload.state, payload);
72
+ const extendContext = extender(op);
73
+ for (const entry of enveloped)
74
+ entry.plugin.onEnveloped?.({
75
+ context: op.context,
76
+ extendContext,
77
+ setSchema: () => {
78
+ throw setSchema(entry.label);
79
+ }
80
+ });
81
+ },
82
+ onContext: (payload) => buildContext(adapter, building, key, payload)
83
+ };
84
+ }
85
+ async function buildContext(adapter, building, key, payload) {
86
+ const op = opOf(key, payload.state, { request: payload.request, params: {} });
87
+ const context = {
88
+ ...op.context,
89
+ ...payload.context
90
+ };
91
+ for (const k of op.extended)
92
+ context[k] = op.context[k];
93
+ const extendContext = (extension) => void Object.assign(context, extension);
94
+ try {
95
+ const afters = [];
96
+ let broken = false;
97
+ for (const { plugin } of building) {
98
+ if (broken)
99
+ break;
100
+ const after = await plugin.onContextBuilding?.({
101
+ context,
102
+ extendContext,
103
+ breakContextBuilding: () => {
104
+ broken = true;
105
+ }
106
+ });
107
+ if (typeof after === "function")
108
+ afters.push(after);
109
+ }
110
+ if (!broken)
111
+ for (const after of afters)
112
+ await after({ context, extendContext });
113
+ } catch (thrown) {
114
+ let error = thrown;
115
+ for (const handler of adapter.errorHandlers)
116
+ await handler({
117
+ context,
118
+ error,
119
+ setError: (next) => {
120
+ error = next;
121
+ }
122
+ });
123
+ if (!(error instanceof GraphQLError))
124
+ throw error;
125
+ op.failure = error;
126
+ }
127
+ return context;
128
+ }
129
+
130
+ // src/document.ts
131
+ import { documentStringMap } from "@envelop/core";
132
+ import { GraphQLError as GraphQLError2, parse, validate } from "graphql";
133
+ function documentHooks(adapter, key) {
134
+ const parsers = adapter.entries.filter((e) => e.plugin.onParse);
135
+ const validators = adapter.entries.filter((e) => e.plugin.onValidate);
136
+ return {
137
+ ...parsers.length > 0 && {
138
+ onParse: (payload) => runParse(parsers, key, payload)
139
+ },
140
+ ...validators.length > 0 && {
141
+ onValidate: (payload) => runValidate(validators, key, payload)
142
+ }
143
+ };
144
+ }
145
+ function runParse(entries, key, payload) {
146
+ const op = opOf(key, payload.state, payload);
147
+ const extendContext = extender(op);
148
+ const source = payload.params.query ?? "";
149
+ let parseFn = parse;
150
+ let document;
151
+ const afters = [];
152
+ try {
153
+ for (const entry of entries) {
154
+ const after = entry.plugin.onParse?.({
155
+ context: op.context,
156
+ extendContext,
157
+ params: { source },
158
+ parseFn,
159
+ setParseFn: (next) => {
160
+ parseFn = next;
161
+ },
162
+ setParsedDocument: (next) => {
163
+ document = next;
164
+ }
165
+ });
166
+ if (typeof after === "function")
167
+ afters.push({ entry, after });
168
+ }
169
+ } catch (error) {
170
+ if (!(error instanceof GraphQLError2))
171
+ throw error;
172
+ payload.setParseFn(() => {
173
+ throw error;
174
+ });
175
+ return () => {};
176
+ }
177
+ if (document)
178
+ payload.setDocument(document);
179
+ else if (parseFn !== parse)
180
+ payload.setParseFn(parseFn);
181
+ return ({ document: parsed }) => {
182
+ if (parsed)
183
+ documentStringMap.set(parsed, source);
184
+ for (const { entry, after } of afters) {
185
+ after({
186
+ context: op.context,
187
+ extendContext,
188
+ result: parsed ?? null,
189
+ replaceParseResult: () => {
190
+ throw replaceParseResult(entry.label);
191
+ }
192
+ });
193
+ }
194
+ };
195
+ }
196
+ function runValidate(entries, key, payload) {
197
+ const op = opOf(key, payload.state, { request: payload.request, params: {} });
198
+ const extendContext = extender(op);
199
+ const { schema, document } = payload;
200
+ let validateFn = validate;
201
+ let result;
202
+ const afters = [];
203
+ for (const entry of entries) {
204
+ const after = entry.plugin.onValidate?.({
205
+ context: op.context,
206
+ extendContext,
207
+ params: { schema, documentAST: document },
208
+ validateFn,
209
+ addValidationRule: (rule) => payload.addRule(rule),
210
+ setValidationFn: (next) => {
211
+ validateFn = next;
212
+ },
213
+ setResult: (errors) => {
214
+ result = errors;
215
+ }
216
+ });
217
+ if (typeof after === "function")
218
+ afters.push({ entry, after });
219
+ }
220
+ if (result)
221
+ payload.setResult(result);
222
+ else if (validateFn !== validate)
223
+ payload.setValidationFn((s, d, rules) => validateFn(s, d, rules));
224
+ return ({ errors }) => {
225
+ if (!errors)
226
+ return;
227
+ for (const { entry, after } of afters) {
228
+ after({
229
+ context: op.context,
230
+ extendContext,
231
+ valid: errors.length === 0,
232
+ result: errors,
233
+ setResult: () => {
234
+ throw afterValidateSetResult(entry.label);
235
+ }
236
+ });
237
+ }
238
+ };
239
+ }
240
+
241
+ // src/execute.ts
242
+ import { GraphQLError as GraphQLError3 } from "graphql";
243
+
244
+ // src/results.ts
245
+ var isAsyncIterable = (value) => typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
246
+ var isIncremental = (value) => typeof value === "object" && value !== null && ("initialResult" in value) && typeof value.subsequentResults?.next === "function";
247
+ function present(output) {
248
+ if (!isIncremental(output))
249
+ return output;
250
+ const { initialResult, subsequentResults } = output;
251
+ let first = true;
252
+ const iterator = {
253
+ [Symbol.asyncIterator]: () => iterator,
254
+ next() {
255
+ if (!first)
256
+ return subsequentResults.next();
257
+ first = false;
258
+ return Promise.resolve({ done: false, value: initialResult });
259
+ },
260
+ return: () => subsequentResults.return?.() ?? Promise.resolve({ done: true, value: undefined })
261
+ };
262
+ return iterator;
263
+ }
264
+ async function rebuild(output) {
265
+ if (!isAsyncIterable(output) || isIncremental(output))
266
+ return output;
267
+ const iterator = output[Symbol.asyncIterator]();
268
+ const first = await iterator.next();
269
+ if (first.done)
270
+ return { data: null };
271
+ return {
272
+ initialResult: first.value,
273
+ subsequentResults: {
274
+ [Symbol.asyncIterator]() {
275
+ return this;
276
+ },
277
+ next: () => iterator.next(),
278
+ return: () => iterator.return?.() ?? Promise.resolve({ done: true, value: undefined }),
279
+ throw: (error) => iterator.throw?.(error) ?? Promise.reject(error)
280
+ }
281
+ };
282
+ }
283
+ function mapPayloads(source, each) {
284
+ const iterator = source[Symbol.asyncIterator]();
285
+ const mapped = {
286
+ [Symbol.asyncIterator]: () => mapped,
287
+ async next() {
288
+ const step = await iterator.next();
289
+ return step.done ? step : { done: false, value: await each(step.value) };
290
+ },
291
+ return: () => iterator.return?.() ?? Promise.resolve({ done: true, value: undefined }),
292
+ throw: (error) => iterator.throw?.(error) ?? Promise.reject(error)
293
+ };
294
+ return mapped;
295
+ }
296
+ function onceDone(source, onEnd) {
297
+ const iterator = source[Symbol.asyncIterator]();
298
+ let done = false;
299
+ const finish = () => {
300
+ if (done)
301
+ return;
302
+ done = true;
303
+ onEnd();
304
+ };
305
+ const wrapped = {
306
+ [Symbol.asyncIterator]: () => wrapped,
307
+ async next() {
308
+ const step = await iterator.next();
309
+ if (step.done)
310
+ finish();
311
+ return step;
312
+ },
313
+ async return(value) {
314
+ try {
315
+ return await iterator.return?.(value) ?? { done: true, value };
316
+ } finally {
317
+ finish();
318
+ }
319
+ },
320
+ throw: (error) => iterator.throw?.(error) ?? Promise.reject(error)
321
+ };
322
+ return wrapped;
323
+ }
324
+ function onFailure(source, onError) {
325
+ const iterator = source[Symbol.asyncIterator]();
326
+ const guarded = {
327
+ [Symbol.asyncIterator]: () => guarded,
328
+ next: () => iterator.next().catch(onError),
329
+ return: () => iterator.return?.() ?? Promise.resolve({ done: true, value: undefined }),
330
+ throw: (error) => iterator.throw?.(error) ?? Promise.reject(error)
331
+ };
332
+ return guarded;
333
+ }
334
+
335
+ // src/execute.ts
336
+ var EXECUTE = {
337
+ hook: "onExecute",
338
+ fn: "executeFn",
339
+ setFn: "setExecuteFn",
340
+ done: "onExecuteDone",
341
+ rebuilds: true
342
+ };
343
+ var SUBSCRIBE = {
344
+ hook: "onSubscribe",
345
+ fn: "subscribeFn",
346
+ setFn: "setSubscribeFn",
347
+ done: "onSubscribeResult",
348
+ rebuilds: false
349
+ };
350
+ function executeHooks(adapter, key) {
351
+ const of = (kind) => {
352
+ const entries = adapter.entries.filter((e) => e.plugin[kind.hook]);
353
+ const asks = entries.length > 0 || adapter.entries.some(needsFailure);
354
+ return asks ? (payload) => run(kind, entries, key, payload) : undefined;
355
+ };
356
+ const onExecute = of(EXECUTE);
357
+ const onSubscribe = of(SUBSCRIBE);
358
+ return {
359
+ ...onExecute && { onExecute },
360
+ ...onSubscribe && { onSubscribe }
361
+ };
362
+ }
363
+ var needsFailure = (entry) => Boolean(entry.plugin.onContextBuilding);
364
+ async function run(kind, entries, key, payload) {
365
+ const failure = payload.state.get(key)?.failure;
366
+ if (failure) {
367
+ payload.setResult({ errors: [failure] });
368
+ return;
369
+ }
370
+ const { args } = payload;
371
+ const context = args.contextValue;
372
+ const initial = payload.executeFn;
373
+ let fn = initial;
374
+ let stopped;
375
+ const afters = [];
376
+ try {
377
+ for (const { plugin } of entries) {
378
+ const after = await plugin[kind.hook]({
379
+ [kind.fn]: fn,
380
+ [kind.setFn]: (next) => {
381
+ fn = next;
382
+ },
383
+ setResultAndStopExecution: (result) => {
384
+ stopped = { result };
385
+ },
386
+ args,
387
+ context,
388
+ extendContext: (extension) => void Object.assign(context, extension)
389
+ });
390
+ if (after)
391
+ afters.push(after);
392
+ if (stopped)
393
+ break;
394
+ }
395
+ } catch (error) {
396
+ if (!(error instanceof GraphQLError3))
397
+ throw error;
398
+ payload.setResult({ errors: [error] });
399
+ return;
400
+ }
401
+ if (stopped)
402
+ payload.setResult(stopped.result);
403
+ else if (fn !== initial)
404
+ payload.setExecuteFn(fn);
405
+ return afters.length > 0 ? (done) => finish(kind, afters, done, args) : undefined;
406
+ }
407
+ async function finish(kind, afters, done, args) {
408
+ if (done.result === undefined)
409
+ return;
410
+ const original = present(done.result);
411
+ let current = original;
412
+ const nexts = [];
413
+ const ends = [];
414
+ for (const after of afters) {
415
+ const hooked = await after[kind.done]?.({
416
+ args,
417
+ result: current,
418
+ setResult: (next) => {
419
+ current = next;
420
+ }
421
+ });
422
+ if (hooked?.onNext)
423
+ nexts.push(hooked.onNext);
424
+ if (hooked?.onEnd)
425
+ ends.push(hooked.onEnd);
426
+ }
427
+ if (nexts.length > 0 && isAsyncIterable(current))
428
+ current = mapPayloads(current, async (payload) => {
429
+ let result = payload;
430
+ for (const onNext of nexts)
431
+ await onNext({
432
+ args,
433
+ result,
434
+ setResult: (next) => {
435
+ result = next;
436
+ }
437
+ });
438
+ return result;
439
+ });
440
+ if (ends.length > 0 && isAsyncIterable(current))
441
+ current = onceDone(current, () => {
442
+ for (const onEnd of ends)
443
+ onEnd();
444
+ });
445
+ const handlers = afters.flatMap((a) => a["onSubscribeError"] ? [a["onSubscribeError"]] : []);
446
+ if (handlers.length > 0 && isAsyncIterable(current))
447
+ current = onFailure(current, (failure) => {
448
+ let error = failure;
449
+ for (const handler of handlers)
450
+ handler({
451
+ error,
452
+ setError: (next) => {
453
+ error = next;
454
+ },
455
+ context: args["contextValue"]
456
+ });
457
+ throw error;
458
+ });
459
+ if (current === original)
460
+ return;
461
+ done.setResult(kind.rebuilds ? await rebuild(current) : current);
462
+ }
463
+
464
+ // src/init.ts
465
+ function flatten(given) {
466
+ const list = [];
467
+ const live = given.filter((plugin) => Boolean(plugin));
468
+ live.forEach((plugin, i) => {
469
+ if (typeof plugin !== "object" || plugin === null)
470
+ throw notAnObject(i + 1, live.length, plugin);
471
+ list.push(plugin);
472
+ });
473
+ const errorHandlers = [];
474
+ for (let i = 0;i < list.length; i++) {
475
+ const plugin = list[i];
476
+ const added = [];
477
+ const label = () => labelOf(i + 1, list.length, plugin);
478
+ plugin.onPluginInit?.({
479
+ plugins: list,
480
+ addPlugin: (next) => void added.push(next),
481
+ setSchema: () => {
482
+ throw setSchema(label());
483
+ },
484
+ registerContextErrorHandler: (handler) => void errorHandlers.push(handler)
485
+ });
486
+ list.splice(i + 1, 0, ...added);
487
+ }
488
+ const entries = list.map((plugin, i) => {
489
+ const label = labelOf(i + 1, list.length, plugin);
490
+ check(plugin, label);
491
+ return { plugin, label };
492
+ });
493
+ return { entries, errorHandlers };
494
+ }
495
+ function check(plugin, label) {
496
+ for (const [key, value] of Object.entries(plugin)) {
497
+ if (value === undefined || SUPPORTED.has(key))
498
+ continue;
499
+ if (key === "instrumentation")
500
+ throw instrumentation(label);
501
+ if (YOGA_KEYS.has(key))
502
+ throw yogaKey(label, key);
503
+ throw unknownKey(label, key);
504
+ }
505
+ }
506
+
507
+ // src/from-envelop.ts
508
+ function fromEnvelop(plugins, options = {}) {
509
+ const adapter = flatten(plugins);
510
+ const key = opKey();
511
+ const plugin = {
512
+ name: options.name ?? "envelop",
513
+ ...options.enforce && { enforce: options.enforce },
514
+ setup({ schema }) {
515
+ for (const { plugin: p, label } of adapter.entries)
516
+ p.onSchemaChange?.({
517
+ schema,
518
+ replaceSchema: () => {
519
+ throw replaceSchema(label);
520
+ }
521
+ });
522
+ },
523
+ ...contextHooks(adapter, key),
524
+ ...documentHooks(adapter, key),
525
+ ...executeHooks(adapter, key)
526
+ };
527
+ return plugin;
528
+ }
529
+ export {
530
+ fromEnvelop
531
+ };
532
+
533
+ //# debugId=11B31D424E942D6164756E2164756E21
534
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,17 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/context.ts", "../src/early-context.ts", "../src/refuse.ts", "../src/document.ts", "../src/execute.ts", "../src/results.ts", "../src/init.ts", "../src/from-envelop.ts"],
4
+ "sourcesContent": [
5
+ "import type { GraxiaPlugin, OnContextPayload } from '@graxia/core';\nimport { GraphQLError } from 'graphql';\nimport { extender, type opKey, opOf } from './early-context';\nimport * as refuse from './refuse';\nimport type { Adapter, Entry } from './types';\n\ntype Key = ReturnType<typeof opKey>;\ntype AfterContext = (payload: unknown) => unknown;\n\n/**\n * `onParams` (Envelop's `onEnveloped`, once per operation) and `onContext`\n * (`onContextBuilding`, its after-hooks at the end) of the adapter. The\n * context the Envelop hooks build on is `{ request, params, ...the host\n * context }`; what they add is returned and merged into graxia's context.\n */\nexport function contextHooks(\n\tadapter: Adapter,\n\tkey: Key,\n): Pick<GraxiaPlugin, 'onParams' | 'onContext'> {\n\tconst { entries } = adapter;\n\tconst enveloped = entries.filter((e) => e.plugin.onEnveloped);\n\tconst building = entries.filter((e) => e.plugin.onContextBuilding);\n\tconst early =\n\t\tenveloped.length > 0 ||\n\t\tbuilding.length > 0 ||\n\t\tentries.some(\n\t\t\t(e) =>\n\t\t\t\te.plugin.onParse ||\n\t\t\t\te.plugin.onValidate ||\n\t\t\t\te.plugin.onExecute ||\n\t\t\t\te.plugin.onSubscribe,\n\t\t);\n\tif (!early) return {};\n\treturn {\n\t\tonParams: (payload) => {\n\t\t\tconst op = opOf(key, payload.state, payload);\n\t\t\tconst extendContext = extender(op);\n\t\t\tfor (const entry of enveloped)\n\t\t\t\tentry.plugin.onEnveloped?.({\n\t\t\t\t\tcontext: op.context,\n\t\t\t\t\textendContext,\n\t\t\t\t\tsetSchema: () => {\n\t\t\t\t\t\tthrow refuse.setSchema(entry.label);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t},\n\t\tonContext: (payload) => buildContext(adapter, building, key, payload),\n\t};\n}\n\nasync function buildContext(\n\tadapter: Adapter,\n\tbuilding: readonly Entry[],\n\tkey: Key,\n\tpayload: OnContextPayload,\n): Promise<Record<PropertyKey, unknown>> {\n\tconst op = opOf(key, payload.state, { request: payload.request, params: {} });\n\tconst context: Record<PropertyKey, unknown> = {\n\t\t...op.context,\n\t\t...payload.context,\n\t};\n\tfor (const k of op.extended) context[k] = op.context[k];\n\tconst extendContext = (extension: object) =>\n\t\tvoid Object.assign(context, extension);\n\ttry {\n\t\tconst afters: AfterContext[] = [];\n\t\tlet broken = false;\n\t\tfor (const { plugin } of building) {\n\t\t\tif (broken) break;\n\t\t\tconst after = await plugin.onContextBuilding?.({\n\t\t\t\tcontext: context as never,\n\t\t\t\textendContext,\n\t\t\t\tbreakContextBuilding: () => {\n\t\t\t\t\tbroken = true;\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (typeof after === 'function') afters.push(after as AfterContext);\n\t\t}\n\t\tif (!broken)\n\t\t\tfor (const after of afters) await after({ context, extendContext });\n\t} catch (thrown) {\n\t\tlet error = thrown;\n\t\tfor (const handler of adapter.errorHandlers)\n\t\t\tawait handler({\n\t\t\t\tcontext,\n\t\t\t\terror,\n\t\t\t\tsetError: (next) => {\n\t\t\t\t\terror = next;\n\t\t\t\t},\n\t\t\t});\n\t\t// A GraphQLError is the client's answer, given by onExecute/onSubscribe.\n\t\tif (!(error instanceof GraphQLError)) throw error;\n\t\top.failure = error;\n\t}\n\treturn context;\n}\n",
6
+ "import { createStateKey, type RequestState } from '@graxia/core';\nimport type { Op } from './types';\n\n/** The per-operation record of one adapter (a key per `fromEnvelop` call). */\nexport const opKey = () => createStateKey<Op>('envelop');\n\n/**\n * The Envelop context of this operation, created on first use:\n * `{ request, params }` first, then what the hooks run before `onContext`\n * (`onEnveloped`, `onParse`, `onValidate`) extend it with.\n */\nexport function opOf(\n\tkey: ReturnType<typeof opKey>,\n\tstate: RequestState,\n\tseed: { request: Request; params: unknown },\n): Op {\n\tconst known = state.get(key);\n\tif (known) return known;\n\tconst op: Op = {\n\t\tcontext: { request: seed.request, params: seed.params },\n\t\textended: new Set(),\n\t};\n\tstate.set(key, op);\n\treturn op;\n}\n\n/** `extendContext` of the early hooks: merges into the context and remembers the keys. */\nexport function extender(op: Op): (extension: object) => void {\n\treturn (extension) => {\n\t\tObject.assign(op.context, extension);\n\t\tfor (const key of Reflect.ownKeys(extension)) op.extended.add(key);\n\t};\n}\n",
7
+ "import { GraxiaConfigError } from '@graxia/core';\n\n/** The Envelop hooks graxia runs. */\nexport const SUPPORTED = new Set([\n\t'onPluginInit',\n\t'onSchemaChange',\n\t'onEnveloped',\n\t'onParse',\n\t'onValidate',\n\t'onContextBuilding',\n\t'onExecute',\n\t'onSubscribe',\n]);\n\n/** Hooks of graphql-yoga plugins: they belong to the HTTP layer graxia replaces. */\nexport const YOGA_KEYS = new Set([\n\t'onRequest',\n\t'onRequestParse',\n\t'onParams',\n\t'onResultProcess',\n\t'onResponse',\n\t'onYogaInit',\n\t'onExecutionResult',\n]);\n\nconst refuse = (message: string) =>\n\tnew GraxiaConfigError(`fromEnvelop: ${message}`);\n\n/** `envelop plugin 2 of 4 (onParse, instrumentation)`. */\nexport function labelOf(index: number, total: number, plugin: object): string {\n\tconst keys = Object.entries(plugin)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([key]) => key);\n\treturn `envelop plugin ${index} of ${total} (${keys.join(', ')})`;\n}\n\nexport const notAnObject = (index: number, total: number, value: unknown) =>\n\trefuse(\n\t\t`entry ${index} of ${total} is ${value === null ? 'null' : typeof value}, not an Envelop plugin object. Pass a plugin such as useDepthLimit({ maxDepth: 10 }), or a falsy value (cond && usePlugin()) to skip one.`,\n\t);\n\nexport const instrumentation = (label: string) =>\n\trefuse(\n\t\t`${label} uses \"instrumentation\", which graxia cannot run. Remove it, or use createGraxia({ telemetry }) or a graxia plugin (definePlugin) instead.`,\n\t);\n\nexport const yogaKey = (label: string, key: string) =>\n\trefuse(\n\t\t`${label} uses \"${key}\": this is a graphql-yoga plugin, not an Envelop one, and graxia cannot run it. Rewrite it with definePlugin from @graxia/core.`,\n\t);\n\nexport const unknownKey = (label: string, key: string) =>\n\trefuse(\n\t\t`${label} uses \"${key}\", which is not an Envelop hook graxia knows. Check the spelling, or write it as a graxia plugin with definePlugin from @graxia/core.`,\n\t);\n\nexport const setSchema = (label: string) =>\n\trefuse(\n\t\t`${label} calls setSchema, which graxia does not honour. Pass the schema to createGraxia({ schema }) instead (useSchema is not needed).`,\n\t);\n\nexport const replaceSchema = (label: string) =>\n\trefuse(\n\t\t`${label} calls replaceSchema, which graxia does not honour: an instance serves the one schema it was created with. Pass the schema to createGraxia({ schema }) instead.`,\n\t);\n\nexport const replaceParseResult = (label: string) =>\n\trefuse(\n\t\t`${label} calls replaceParseResult, which graxia does not honour. Use setParsedDocument in onParse, or throw a GraphQLError there, instead.`,\n\t);\n\nexport const afterValidateSetResult = (label: string) =>\n\trefuse(\n\t\t`${label} calls setResult in the after-hook of onValidate, which graxia does not honour. Call setResult in onValidate itself, or write a graxia plugin (definePlugin) that replaces the errors.`,\n\t);\n",
8
+ "import { documentStringMap } from '@envelop/core';\nimport type {\n\tGraxiaPlugin,\n\tOnParseDone,\n\tOnParsePayload,\n\tOnValidateDone,\n\tOnValidatePayload,\n} from '@graxia/core';\nimport { GraphQLError, parse, validate } from 'graphql';\nimport { extender, type opKey, opOf } from './early-context';\nimport * as refuse from './refuse';\nimport type { Adapter, Entry } from './types';\n\ntype Key = ReturnType<typeof opKey>;\ntype Hooks = Pick<GraxiaPlugin, 'onParse' | 'onValidate'>;\ntype Maybe<T> = T | undefined;\n\n/** `onParse` and `onValidate` of the adapter: the Envelop plugins' hooks of the same names, in order. */\nexport function documentHooks(adapter: Adapter, key: Key): Hooks {\n\tconst parsers = adapter.entries.filter((e) => e.plugin.onParse);\n\tconst validators = adapter.entries.filter((e) => e.plugin.onValidate);\n\treturn {\n\t\t...(parsers.length > 0 && {\n\t\t\tonParse: (payload) => runParse(parsers, key, payload),\n\t\t}),\n\t\t...(validators.length > 0 && {\n\t\t\tonValidate: (payload) => runValidate(validators, key, payload),\n\t\t}),\n\t};\n}\n\ntype AfterParse = (payload: never) => unknown;\n\nfunction runParse(\n\tentries: readonly Entry[],\n\tkey: Key,\n\tpayload: OnParsePayload,\n): (done: OnParseDone) => void {\n\tconst op = opOf(key, payload.state, payload);\n\tconst extendContext = extender(op);\n\tconst source = payload.params.query ?? '';\n\tlet parseFn: (source: string) => unknown = parse;\n\tlet document: unknown;\n\tconst afters: { entry: Entry; after: AfterParse }[] = [];\n\ttry {\n\t\tfor (const entry of entries) {\n\t\t\tconst after = entry.plugin.onParse?.({\n\t\t\t\tcontext: op.context,\n\t\t\t\textendContext,\n\t\t\t\tparams: { source },\n\t\t\t\tparseFn: parseFn as never,\n\t\t\t\tsetParseFn: (next) => {\n\t\t\t\t\tparseFn = next as never;\n\t\t\t\t},\n\t\t\t\tsetParsedDocument: (next) => {\n\t\t\t\t\tdocument = next;\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (typeof after === 'function')\n\t\t\t\tafters.push({ entry, after: after as AfterParse });\n\t\t}\n\t} catch (error) {\n\t\t// A GraphQLError is the client's answer: it is raised from the parse step,\n\t\t// which core answers with it (an `onParse` hook that throws is a 500).\n\t\tif (!(error instanceof GraphQLError)) throw error;\n\t\tpayload.setParseFn(() => {\n\t\t\tthrow error;\n\t\t});\n\t\treturn () => {};\n\t}\n\tif (document) payload.setDocument(document as never);\n\telse if (parseFn !== parse) payload.setParseFn(parseFn as never);\n\treturn ({ document: parsed }) => {\n\t\tif (parsed) documentStringMap.set(parsed, source);\n\t\tfor (const { entry, after } of afters) {\n\t\t\t(after as (p: unknown) => void)({\n\t\t\t\tcontext: op.context,\n\t\t\t\textendContext,\n\t\t\t\tresult: parsed ?? null,\n\t\t\t\treplaceParseResult: () => {\n\t\t\t\t\tthrow refuse.replaceParseResult(entry.label);\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t};\n}\n\nfunction runValidate(\n\tentries: readonly Entry[],\n\tkey: Key,\n\tpayload: OnValidatePayload,\n): (done: OnValidateDone) => void {\n\tconst op = opOf(key, payload.state, { request: payload.request, params: {} });\n\tconst extendContext = extender(op);\n\tconst { schema, document } = payload;\n\tlet validateFn: (...args: never[]) => unknown = validate as never;\n\tlet result: Maybe<readonly GraphQLError[]>;\n\tconst afters: { entry: Entry; after: AfterParse }[] = [];\n\tfor (const entry of entries) {\n\t\tconst after = entry.plugin.onValidate?.({\n\t\t\tcontext: op.context,\n\t\t\textendContext,\n\t\t\tparams: { schema, documentAST: document },\n\t\t\tvalidateFn: validateFn as never,\n\t\t\taddValidationRule: (rule) => payload.addRule(rule),\n\t\t\tsetValidationFn: (next) => {\n\t\t\t\tvalidateFn = next as never;\n\t\t\t},\n\t\t\tsetResult: (errors) => {\n\t\t\t\tresult = errors as GraphQLError[];\n\t\t\t},\n\t\t});\n\t\tif (typeof after === 'function')\n\t\t\tafters.push({ entry, after: after as AfterParse });\n\t}\n\tif (result) payload.setResult(result);\n\telse if (validateFn !== (validate as never))\n\t\tpayload.setValidationFn((s, d, rules) =>\n\t\t\t(validateFn as (...a: unknown[]) => readonly GraphQLError[])(s, d, rules),\n\t\t);\n\treturn ({ errors }) => {\n\t\tif (!errors) return;\n\t\tfor (const { entry, after } of afters) {\n\t\t\t(after as (p: unknown) => void)({\n\t\t\t\tcontext: op.context,\n\t\t\t\textendContext,\n\t\t\t\tvalid: errors.length === 0,\n\t\t\t\tresult: errors,\n\t\t\t\tsetResult: () => {\n\t\t\t\t\tthrow refuse.afterValidateSetResult(entry.label);\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t};\n}\n",
9
+ "import type {\n\tExecutionOutput,\n\tGraxiaPlugin,\n\tOnExecuteDone,\n\tOnExecutePayload,\n} from '@graxia/core';\nimport { GraphQLError } from 'graphql';\nimport type { opKey } from './early-context';\nimport {\n\tisAsyncIterable,\n\tmapPayloads,\n\tonceDone,\n\tonFailure,\n\tpresent,\n\trebuild,\n} from './results';\nimport type { Adapter, Entry } from './types';\n\ntype Key = ReturnType<typeof opKey>;\ntype Loose = any;\n\n/** What differs between `onExecute` and `onSubscribe`: the names of the Envelop hooks and of their payload members. */\ninterface Kind {\n\thook: 'onExecute' | 'onSubscribe';\n\tfn: 'executeFn' | 'subscribeFn';\n\tsetFn: 'setExecuteFn' | 'setSubscribeFn';\n\tdone: 'onExecuteDone' | 'onSubscribeResult';\n\t/** A query's incremental result is rebuilt from the payloads the hooks saw; a subscription stays a stream. */\n\trebuilds: boolean;\n}\n\nconst EXECUTE: Kind = {\n\thook: 'onExecute',\n\tfn: 'executeFn',\n\tsetFn: 'setExecuteFn',\n\tdone: 'onExecuteDone',\n\trebuilds: true,\n};\nconst SUBSCRIBE: Kind = {\n\thook: 'onSubscribe',\n\tfn: 'subscribeFn',\n\tsetFn: 'setSubscribeFn',\n\tdone: 'onSubscribeResult',\n\trebuilds: false,\n};\n\n/** `onExecute` and `onSubscribe` of the adapter, with their done hooks as after-hooks. */\nexport function executeHooks(\n\tadapter: Adapter,\n\tkey: Key,\n): Pick<GraxiaPlugin, 'onExecute' | 'onSubscribe'> {\n\tconst of = (kind: Kind) => {\n\t\tconst entries = adapter.entries.filter((e) => e.plugin[kind.hook]);\n\t\tconst asks = entries.length > 0 || adapter.entries.some(needsFailure);\n\t\treturn asks\n\t\t\t? (payload: OnExecutePayload) => run(kind, entries, key, payload)\n\t\t\t: undefined;\n\t};\n\tconst onExecute = of(EXECUTE);\n\tconst onSubscribe = of(SUBSCRIBE);\n\treturn {\n\t\t...(onExecute && { onExecute }),\n\t\t...(onSubscribe && { onSubscribe }),\n\t};\n}\n\nconst needsFailure = (entry: Entry) => Boolean(entry.plugin.onContextBuilding);\n\nasync function run(\n\tkind: Kind,\n\tentries: readonly Entry[],\n\tkey: Key,\n\tpayload: OnExecutePayload,\n): Promise<((done: OnExecuteDone) => Promise<void>) | undefined> {\n\tconst failure = payload.state.get(key)?.failure;\n\tif (failure) {\n\t\tpayload.setResult({ errors: [failure] });\n\t\treturn undefined;\n\t}\n\tconst { args } = payload;\n\tconst context = args.contextValue as Record<string, unknown>;\n\tconst initial = payload.executeFn;\n\tlet fn = initial;\n\tlet stopped: { result: ExecutionOutput } | undefined;\n\tconst afters: Loose[] = [];\n\ttry {\n\t\tfor (const { plugin } of entries) {\n\t\t\tconst after = await (plugin[kind.hook] as Loose)({\n\t\t\t\t[kind.fn]: fn,\n\t\t\t\t[kind.setFn]: (next: typeof fn) => {\n\t\t\t\t\tfn = next;\n\t\t\t\t},\n\t\t\t\tsetResultAndStopExecution: (result: ExecutionOutput) => {\n\t\t\t\t\tstopped = { result };\n\t\t\t\t},\n\t\t\t\targs,\n\t\t\t\tcontext,\n\t\t\t\textendContext: (extension: object) =>\n\t\t\t\t\tvoid Object.assign(context, extension),\n\t\t\t});\n\t\t\tif (after) afters.push(after);\n\t\t\tif (stopped) break;\n\t\t}\n\t} catch (error) {\n\t\t// A GraphQLError is the client's answer; anything else is unexpected.\n\t\tif (!(error instanceof GraphQLError)) throw error;\n\t\tpayload.setResult({ errors: [error] });\n\t\treturn undefined;\n\t}\n\tif (stopped) payload.setResult(stopped.result);\n\telse if (fn !== initial) payload.setExecuteFn(fn);\n\treturn afters.length > 0\n\t\t? (done) => finish(kind, afters, done, args)\n\t\t: undefined;\n}\n\nasync function finish(\n\tkind: Kind,\n\tafters: readonly Loose[],\n\tdone: OnExecuteDone,\n\targs: object,\n): Promise<void> {\n\tif (done.result === undefined) return;\n\tconst original = present(done.result);\n\tlet current = original;\n\tconst nexts: Loose[] = [];\n\tconst ends: (() => void)[] = [];\n\tfor (const after of afters) {\n\t\tconst hooked = await after[kind.done]?.({\n\t\t\targs,\n\t\t\tresult: current,\n\t\t\tsetResult: (next: unknown) => {\n\t\t\t\tcurrent = next;\n\t\t\t},\n\t\t});\n\t\tif (hooked?.onNext) nexts.push(hooked.onNext);\n\t\tif (hooked?.onEnd) ends.push(hooked.onEnd);\n\t}\n\tif (nexts.length > 0 && isAsyncIterable(current))\n\t\tcurrent = mapPayloads(current, async (payload) => {\n\t\t\tlet result = payload;\n\t\t\tfor (const onNext of nexts)\n\t\t\t\tawait onNext({\n\t\t\t\t\targs,\n\t\t\t\t\tresult,\n\t\t\t\t\tsetResult: (next: unknown) => {\n\t\t\t\t\t\tresult = next;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\treturn result;\n\t\t});\n\tif (ends.length > 0 && isAsyncIterable(current))\n\t\tcurrent = onceDone(current, () => {\n\t\t\tfor (const onEnd of ends) onEnd();\n\t\t});\n\tconst handlers = afters.flatMap((a) =>\n\t\ta['onSubscribeError'] ? [a['onSubscribeError'] as (p: object) => void] : [],\n\t);\n\tif (handlers.length > 0 && isAsyncIterable(current))\n\t\tcurrent = onFailure(current, (failure) => {\n\t\t\tlet error = failure;\n\t\t\tfor (const handler of handlers)\n\t\t\t\thandler({\n\t\t\t\t\terror,\n\t\t\t\t\tsetError: (next: unknown) => {\n\t\t\t\t\t\terror = next;\n\t\t\t\t\t},\n\t\t\t\t\tcontext: (args as Loose)['contextValue'],\n\t\t\t\t});\n\t\t\tthrow error;\n\t\t});\n\tif (current === original) return;\n\tdone.setResult(kind.rebuilds ? await rebuild(current) : (current as never));\n}\n",
10
+ "import type { ExecutionOutput } from '@graxia/core';\n\nexport const isAsyncIterable = (\n\tvalue: unknown,\n): value is AsyncIterable<unknown> =>\n\ttypeof value === 'object' &&\n\tvalue !== null &&\n\ttypeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function';\n\ninterface Incremental {\n\tinitialResult: unknown;\n\tsubsequentResults: AsyncIterator<unknown>;\n}\n\nconst isIncremental = (value: unknown): value is Incremental =>\n\ttypeof value === 'object' &&\n\tvalue !== null &&\n\t'initialResult' in value &&\n\ttypeof (value as Incremental).subsequentResults?.next === 'function';\n\n/**\n * The result as Envelop's done-hooks expect it: an incremental result\n * (`{ initialResult, subsequentResults }`) becomes an async iterable of its\n * payloads, anything else stays as is.\n */\nexport function present(output: unknown): unknown {\n\tif (!isIncremental(output)) return output;\n\tconst { initialResult, subsequentResults } = output;\n\tlet first = true;\n\tconst iterator: AsyncIterableIterator<unknown> = {\n\t\t[Symbol.asyncIterator]: () => iterator,\n\t\tnext() {\n\t\t\tif (!first) return subsequentResults.next();\n\t\t\tfirst = false;\n\t\t\treturn Promise.resolve({ done: false, value: initialResult });\n\t\t},\n\t\treturn: () =>\n\t\t\tsubsequentResults.return?.() ??\n\t\t\tPromise.resolve({ done: true, value: undefined }),\n\t};\n\treturn iterator;\n}\n\n/**\n * The inverse of {@link present} for a query: an async iterable of payloads\n * is pulled for its first one and rebuilt as `{ initialResult, subsequentResults }`.\n */\nexport async function rebuild(output: unknown): Promise<ExecutionOutput> {\n\tif (!isAsyncIterable(output) || isIncremental(output))\n\t\treturn output as ExecutionOutput;\n\tconst iterator = output[Symbol.asyncIterator]();\n\tconst first = await iterator.next();\n\tif (first.done) return { data: null } as ExecutionOutput;\n\treturn {\n\t\tinitialResult: first.value,\n\t\tsubsequentResults: {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tnext: () => iterator.next(),\n\t\t\treturn: () =>\n\t\t\t\titerator.return?.() ??\n\t\t\t\tPromise.resolve({ done: true, value: undefined }),\n\t\t\tthrow: (error: unknown) =>\n\t\t\t\titerator.throw?.(error) ?? Promise.reject(error),\n\t\t},\n\t} as unknown as ExecutionOutput;\n}\n\n/** Runs `each` on every payload of `source`, which may replace it (`onNext`). */\nexport function mapPayloads(\n\tsource: AsyncIterable<unknown>,\n\teach: (payload: unknown) => Promise<unknown>,\n): AsyncIterableIterator<unknown> {\n\tconst iterator = source[Symbol.asyncIterator]();\n\tconst mapped: AsyncIterableIterator<unknown> = {\n\t\t[Symbol.asyncIterator]: () => mapped,\n\t\tasync next() {\n\t\t\tconst step = await iterator.next();\n\t\t\treturn step.done ? step : { done: false, value: await each(step.value) };\n\t\t},\n\t\treturn: () =>\n\t\t\titerator.return?.() ?? Promise.resolve({ done: true, value: undefined }),\n\t\tthrow: (error) => iterator.throw?.(error) ?? Promise.reject(error),\n\t};\n\treturn mapped;\n}\n\n/** Calls `onEnd` once, when `source` is exhausted or released (`onEnd`). */\nexport function onceDone(\n\tsource: AsyncIterable<unknown>,\n\tonEnd: () => void,\n): AsyncIterableIterator<unknown> {\n\tconst iterator = source[Symbol.asyncIterator]();\n\tlet done = false;\n\tconst finish = () => {\n\t\tif (done) return;\n\t\tdone = true;\n\t\tonEnd();\n\t};\n\tconst wrapped: AsyncIterableIterator<unknown> = {\n\t\t[Symbol.asyncIterator]: () => wrapped,\n\t\tasync next() {\n\t\t\tconst step = await iterator.next();\n\t\t\tif (step.done) finish();\n\t\t\treturn step;\n\t\t},\n\t\tasync return(value) {\n\t\t\ttry {\n\t\t\t\treturn (await iterator.return?.(value)) ?? { done: true, value };\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t}\n\t\t},\n\t\tthrow: (error) => iterator.throw?.(error) ?? Promise.reject(error),\n\t};\n\treturn wrapped;\n}\n\n/** Hands a failure of `source` to `onError`, which throws the (maybe replaced) error (`onSubscribeError`). */\nexport function onFailure(\n\tsource: AsyncIterable<unknown>,\n\tonError: (error: unknown) => never,\n): AsyncIterableIterator<unknown> {\n\tconst iterator = source[Symbol.asyncIterator]();\n\tconst guarded: AsyncIterableIterator<unknown> = {\n\t\t[Symbol.asyncIterator]: () => guarded,\n\t\tnext: () => iterator.next().catch(onError),\n\t\treturn: () =>\n\t\t\titerator.return?.() ?? Promise.resolve({ done: true, value: undefined }),\n\t\tthrow: (error) => iterator.throw?.(error) ?? Promise.reject(error),\n\t};\n\treturn guarded;\n}\n",
11
+ "import * as refuse from './refuse';\nimport type { Adapter, AnyPlugin, ContextErrorHandler, Entry } from './types';\n\n/**\n * Flattens the given plugins the way Envelop's orchestrator does: runs each\n * `onPluginInit`, inserts the plugins it adds right after it (their own\n * `onPluginInit` runs in turn), collects the context error handlers, then\n * checks every hook name. Everything graxia cannot run is refused here, at\n * boot.\n */\nexport function flatten(\n\tgiven: readonly (AnyPlugin | false | null | undefined)[],\n): Adapter {\n\tconst list: AnyPlugin[] = [];\n\tconst live = given.filter((plugin) => Boolean(plugin));\n\tlive.forEach((plugin, i) => {\n\t\tif (typeof plugin !== 'object' || plugin === null)\n\t\t\tthrow refuse.notAnObject(i + 1, live.length, plugin);\n\t\tlist.push(plugin);\n\t});\n\tconst errorHandlers: ContextErrorHandler[] = [];\n\tfor (let i = 0; i < list.length; i++) {\n\t\tconst plugin = list[i] as AnyPlugin;\n\t\tconst added: AnyPlugin[] = [];\n\t\tconst label = () => refuse.labelOf(i + 1, list.length, plugin);\n\t\tplugin.onPluginInit?.({\n\t\t\tplugins: list,\n\t\t\taddPlugin: (next) => void added.push(next as AnyPlugin),\n\t\t\tsetSchema: () => {\n\t\t\t\tthrow refuse.setSchema(label());\n\t\t\t},\n\t\t\tregisterContextErrorHandler: (handler) =>\n\t\t\t\tvoid errorHandlers.push(handler as ContextErrorHandler),\n\t\t});\n\t\tlist.splice(i + 1, 0, ...added);\n\t}\n\tconst entries = list.map((plugin, i): Entry => {\n\t\tconst label = refuse.labelOf(i + 1, list.length, plugin);\n\t\tcheck(plugin, label);\n\t\treturn { plugin, label };\n\t});\n\treturn { entries, errorHandlers };\n}\n\nfunction check(plugin: AnyPlugin, label: string): void {\n\tfor (const [key, value] of Object.entries(plugin)) {\n\t\tif (value === undefined || refuse.SUPPORTED.has(key)) continue;\n\t\tif (key === 'instrumentation') throw refuse.instrumentation(label);\n\t\tif (refuse.YOGA_KEYS.has(key)) throw refuse.yogaKey(label, key);\n\t\tthrow refuse.unknownKey(label, key);\n\t}\n}\n",
12
+ "import type { Plugin as EnvelopPlugin } from '@envelop/core';\nimport type { Empty, GraxiaPlugin } from '@graxia/core';\nimport { contextHooks } from './context';\nimport { documentHooks } from './document';\nimport { opKey } from './early-context';\nimport { executeHooks } from './execute';\nimport { flatten } from './init';\nimport * as refuse from './refuse';\n\n/** Options of {@link fromEnvelop}. */\nexport interface FromEnvelopOptions {\n\t/** The graxia plugin's name (default `envelop`). Two adapters in one instance need distinct names. */\n\tname?: string;\n\t/** Where the adapter runs among the other plugins. */\n\tenforce?: 'pre' | 'post';\n}\n\n/**\n * Runs Envelop plugins inside graxia as one graxia plugin.\n *\n * Every Envelop hook graxia can honour is mapped onto its own stages; any\n * other hook (`instrumentation`, a graphql-yoga hook, an unknown name) is\n * refused here, at boot, with a `GraxiaConfigError` that says what to write\n * instead. `Added` is what the plugins put in the context (unchecked).\n *\n * @example\n * createGraxia({\n * schema,\n * plugins: [fromEnvelop([useDepthLimit({ maxDepth: 10 })])],\n * }).serve();\n */\nexport function fromEnvelop<Added extends object = Empty>(\n\tplugins: readonly (EnvelopPlugin<any> | false | null | undefined)[],\n\toptions: FromEnvelopOptions = {},\n): GraxiaPlugin<Empty, Added> {\n\tconst adapter = flatten(plugins);\n\tconst key = opKey();\n\tconst plugin: GraxiaPlugin<Empty, Empty> = {\n\t\tname: options.name ?? 'envelop',\n\t\t...(options.enforce && { enforce: options.enforce }),\n\t\tsetup({ schema }) {\n\t\t\tfor (const { plugin: p, label } of adapter.entries)\n\t\t\t\tp.onSchemaChange?.({\n\t\t\t\t\tschema,\n\t\t\t\t\treplaceSchema: () => {\n\t\t\t\t\t\tthrow refuse.replaceSchema(label);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t},\n\t\t...contextHooks(adapter, key),\n\t\t...documentHooks(adapter, key),\n\t\t...executeHooks(adapter, key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.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Adapter, AnyPlugin } from './types.js';
2
+ /**
3
+ * Flattens the given plugins the way Envelop's orchestrator does: runs each
4
+ * `onPluginInit`, inserts the plugins it adds right after it (their own
5
+ * `onPluginInit` runs in turn), collects the context error handlers, then
6
+ * checks every hook name. Everything graxia cannot run is refused here, at
7
+ * boot.
8
+ */
9
+ export declare function flatten(given: readonly (AnyPlugin | false | null | undefined)[]): Adapter;
10
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAA8B,MAAM,SAAS,CAAC;AAE9E;;;;;;GAMG;AACH,wBAAgB,OAAO,CACtB,KAAK,EAAE,SAAS,CAAC,SAAS,GAAG,KAAK,GAAG,IAAI,GAAG,SAAS,CAAC,EAAE,GACtD,OAAO,CA8BT"}
@@ -0,0 +1,16 @@
1
+ import { GraxiaConfigError } from '@graxia/core';
2
+ /** The Envelop hooks graxia runs. */
3
+ export declare const SUPPORTED: Set<string>;
4
+ /** Hooks of graphql-yoga plugins: they belong to the HTTP layer graxia replaces. */
5
+ export declare const YOGA_KEYS: Set<string>;
6
+ /** `envelop plugin 2 of 4 (onParse, instrumentation)`. */
7
+ export declare function labelOf(index: number, total: number, plugin: object): string;
8
+ export declare const notAnObject: (index: number, total: number, value: unknown) => GraxiaConfigError;
9
+ export declare const instrumentation: (label: string) => GraxiaConfigError;
10
+ export declare const yogaKey: (label: string, key: string) => GraxiaConfigError;
11
+ export declare const unknownKey: (label: string, key: string) => GraxiaConfigError;
12
+ export declare const setSchema: (label: string) => GraxiaConfigError;
13
+ export declare const replaceSchema: (label: string) => GraxiaConfigError;
14
+ export declare const replaceParseResult: (label: string) => GraxiaConfigError;
15
+ export declare const afterValidateSetResult: (label: string) => GraxiaConfigError;
16
+ //# sourceMappingURL=refuse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refuse.d.ts","sourceRoot":"","sources":["../src/refuse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,qCAAqC;AACrC,eAAO,MAAM,SAAS,aASpB,CAAC;AAEH,oFAAoF;AACpF,eAAO,MAAM,SAAS,aAQpB,CAAC;AAKH,0DAA0D;AAC1D,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAK5E;AAED,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,EAAE,OAAO,MAAM,EAAE,OAAO,OAAO,sBAGtE,CAAC;AAEH,eAAO,MAAM,eAAe,GAAI,OAAO,MAAM,sBAG3C,CAAC;AAEH,eAAO,MAAM,OAAO,GAAI,OAAO,MAAM,EAAE,KAAK,MAAM,sBAGhD,CAAC;AAEH,eAAO,MAAM,UAAU,GAAI,OAAO,MAAM,EAAE,KAAK,MAAM,sBAGnD,CAAC;AAEH,eAAO,MAAM,SAAS,GAAI,OAAO,MAAM,sBAGrC,CAAC;AAEH,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,sBAGzC,CAAC;AAEH,eAAO,MAAM,kBAAkB,GAAI,OAAO,MAAM,sBAG9C,CAAC;AAEH,eAAO,MAAM,sBAAsB,GAAI,OAAO,MAAM,sBAGlD,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { ExecutionOutput } from '@graxia/core';
2
+ export declare const isAsyncIterable: (value: unknown) => value is AsyncIterable<unknown>;
3
+ /**
4
+ * The result as Envelop's done-hooks expect it: an incremental result
5
+ * (`{ initialResult, subsequentResults }`) becomes an async iterable of its
6
+ * payloads, anything else stays as is.
7
+ */
8
+ export declare function present(output: unknown): unknown;
9
+ /**
10
+ * The inverse of {@link present} for a query: an async iterable of payloads
11
+ * is pulled for its first one and rebuilt as `{ initialResult, subsequentResults }`.
12
+ */
13
+ export declare function rebuild(output: unknown): Promise<ExecutionOutput>;
14
+ /** Runs `each` on every payload of `source`, which may replace it (`onNext`). */
15
+ export declare function mapPayloads(source: AsyncIterable<unknown>, each: (payload: unknown) => Promise<unknown>): AsyncIterableIterator<unknown>;
16
+ /** Calls `onEnd` once, when `source` is exhausted or released (`onEnd`). */
17
+ export declare function onceDone(source: AsyncIterable<unknown>, onEnd: () => void): AsyncIterableIterator<unknown>;
18
+ /** Hands a failure of `source` to `onError`, which throws the (maybe replaced) error (`onSubscribeError`). */
19
+ export declare function onFailure(source: AsyncIterable<unknown>, onError: (error: unknown) => never): AsyncIterableIterator<unknown>;
20
+ //# sourceMappingURL=results.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"results.d.ts","sourceRoot":"","sources":["../src/results.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD,eAAO,MAAM,eAAe,GAC3B,OAAO,OAAO,KACZ,KAAK,IAAI,aAAa,CAAC,OAAO,CAG6C,CAAC;AAa/E;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAgBhD;AAED;;;GAGG;AACH,wBAAsB,OAAO,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,CAAC,CAoBvE;AAED,iFAAiF;AACjF,wBAAgB,WAAW,CAC1B,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,GAC1C,qBAAqB,CAAC,OAAO,CAAC,CAahC;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CACvB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,KAAK,EAAE,MAAM,IAAI,GACf,qBAAqB,CAAC,OAAO,CAAC,CAyBhC;AAED,8GAA8G;AAC9G,wBAAgB,SAAS,CACxB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,GAChC,qBAAqB,CAAC,OAAO,CAAC,CAUhC"}
@@ -0,0 +1,29 @@
1
+ import type { Plugin } from '@envelop/core';
2
+ import type { GraphQLError } from 'graphql';
3
+ /** Any Envelop plugin, whatever context it declares. */
4
+ export type AnyPlugin = Plugin<any>;
5
+ /** An Envelop plugin with the label its errors use: `envelop plugin 2 of 4 (onParse, instrumentation)`. */
6
+ export interface Entry {
7
+ plugin: AnyPlugin;
8
+ label: string;
9
+ }
10
+ /** What the Envelop context held for one operation before graxia built its own. */
11
+ export interface Op {
12
+ /** `{ request, params, ...what onEnveloped/onParse/onValidate extended }`, the `context` those hooks see. */
13
+ readonly context: Record<PropertyKey, unknown>;
14
+ /** The keys those hooks extended: they win over the host context in `onContext`. */
15
+ readonly extended: Set<PropertyKey>;
16
+ /** A `GraphQLError` an `onContextBuilding` hook raised: answered by `onExecute`/`onSubscribe`. */
17
+ failure?: GraphQLError;
18
+ }
19
+ /** The graxia plugin's shared, read-only view of the adapted Envelop plugins. */
20
+ export interface Adapter {
21
+ readonly entries: readonly Entry[];
22
+ readonly errorHandlers: readonly ContextErrorHandler[];
23
+ }
24
+ export type ContextErrorHandler = (payload: {
25
+ context: Readonly<Record<string, unknown>>;
26
+ error: unknown;
27
+ setError: (error: unknown) => void;
28
+ }) => void | Promise<void>;
29
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C,wDAAwD;AACxD,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAEpC,2GAA2G;AAC3G,MAAM,WAAW,KAAK;IACrB,MAAM,EAAE,SAAS,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACd;AAED,mFAAmF;AACnF,MAAM,WAAW,EAAE;IAClB,6GAA6G;IAC7G,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IAC/C,oFAAoF;IACpF,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IACpC,kGAAkG;IAClG,OAAO,CAAC,EAAE,YAAY,CAAC;CACvB;AAED,iFAAiF;AACjF,MAAM,WAAW,OAAO;IACvB,QAAQ,CAAC,OAAO,EAAE,SAAS,KAAK,EAAE,CAAC;IACnC,QAAQ,CAAC,aAAa,EAAE,SAAS,mBAAmB,EAAE,CAAC;CACvD;AAED,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,EAAE;IAC3C,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3C,KAAK,EAAE,OAAO,CAAC;IACf,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACnC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC"}
package/docs/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @graxia/envelop documentation
2
+
3
+ `@graxia/envelop` runs Envelop plugins inside graxia. The [npm page](../README.md) has the quick start; these pages go
4
+ deeper.
5
+
6
+ ## Guides
7
+
8
+ - [Running Envelop plugins](./guide/envelop.md): the hook mapping, the context timeline, errors, `@defer` and
9
+ subscriptions, migrating from graphql-yoga, and the tested plugins.
10
+
11
+ ## Help
12
+
13
+ - [Troubleshooting](./troubleshooting.md): every error message, why it happens and the fix.
14
+
15
+ ## What is next
16
+
17
+ - [Roadmap](./roadmap.md): what you get now and what is next.
@@ -0,0 +1,99 @@
1
+ # Running Envelop plugins
2
+
3
+ ```ts
4
+ import { createGraxia } from '@graxia/core';
5
+ import { fromEnvelop } from '@graxia/envelop';
6
+ import { useDepthLimit } from '@envelop/depth-limit';
7
+
8
+ createGraxia({
9
+ schema,
10
+ plugins: [fromEnvelop([useDepthLimit({ maxDepth: 10 })])],
11
+ }).serve();
12
+ ```
13
+
14
+ `fromEnvelop(plugins, options?)` takes the list you would give `envelop()` and returns one graxia plugin. Options: `name`
15
+ (default `envelop`; two adapters in one instance need distinct names) and `enforce` (`'pre'` or `'post'`, where it runs among
16
+ the other plugins).
17
+
18
+ The plugins are checked when `fromEnvelop` is called, so a plugin graxia cannot run fails at boot, not on the first
19
+ request.
20
+
21
+ ## Hook mapping
22
+
23
+ | Envelop hook | Runs at graxia stage | Notes |
24
+ | ------------------------------------------------------------------ | -------------------- | ------------------------------------------------------------------------------------------------- |
25
+ | `onPluginInit` | `fromEnvelop()` call | `addPlugin` inserts after the adder, recursively. `setSchema` is refused. |
26
+ | `onSchemaChange` | `setup` | Called once with the schema. `replaceSchema` is refused. |
27
+ | `onEnveloped` | `onParams` | Once per operation (once per batch entry). |
28
+ | `onParse` (`setParsedDocument`, `setParseFn`) | `onParse` | `setParseFn` keeps core's token limit. Its after-hook sees the document, or `null`. |
29
+ | `onValidate` (`addValidationRule`, `setValidationFn`, `setResult`) | `onValidate` | Validation errors answer 400. `replaceParseResult` and `setResult` in the after-hook are refused. |
30
+ | `onContextBuilding` | `onContext` | `extendContext`, `breakContextBuilding` and the after-hook work. |
31
+ | `onExecute`, `onExecuteDone` | `onExecute` | `setExecuteFn`, `setResultAndStopExecution`, `setResult`. |
32
+ | `onSubscribe`, `onSubscribeResult` | `onSubscribe` | `onNext`, `onEnd`, and `onSubscribeError` with `setError`. |
33
+ | `instrumentation`, graphql-yoga hooks | not run | Refused at boot, see [troubleshooting](../troubleshooting.md). |
34
+
35
+ ## The context
36
+
37
+ The context the Envelop hooks build on is `{ request, params, ...your host context }`. Keys the hooks add with
38
+ `extendContext` are merged into graxia's context and reach the resolvers. A `GraphQLError` thrown in
39
+ `onContextBuilding` answers `{ errors }` without running a resolver; any other error is a masked 500 reported to
40
+ `onUnexpected`, after the handlers registered with `registerContextErrorHandler` ran (they may `setError`).
41
+
42
+ graxia builds one context object per operation, so a plugin that keeps a reference to the context object across
43
+ hooks sees the one it was given at each hook, not an identical object. Known limit: `@envelop/generic-auth`'s
44
+ `extractPolicies` / `@policy` is not supported (it relies on that identity): a `@policy`-protected field is denied, never served. `serverContext` is not part of the early
45
+ context.
46
+
47
+ ### What the resolver context holds
48
+
49
+ Resolvers receive your own context (the `context` option, plus what other graxia plugins add), then `request` and `params`
50
+ from the adapter, then the keys the Envelop hooks added with `extendContext`. Your own keys win over `request` and
51
+ `params`; keys a hook extended win over your own. `@envelop/core` is a runtime peer of the package.
52
+
53
+ ## What stays in force
54
+
55
+ - A plugin's `setParsedDocument` skips parsing, so it also skips core's token limit; core's validation rules still run,
56
+ because the adapter hands core's `rules` to a custom validate function.
57
+ - A plugin whose `setValidationFn` drops `rules` skips them: that is the plugin's own choice.
58
+
59
+ ## Errors
60
+
61
+ - A `GraphQLError` thrown in a hook is the client's answer and keeps its message and `extensions.code`.
62
+ - A plain `Error` is unexpected: masked, and reported through `onUnexpected`.
63
+ - A `GraphQLError` with its own `extensions.code` thrown in `onParse` keeps it; syntax errors get
64
+ `GRAPHQL_PARSE_FAILED`.
65
+ - `@envelop/generic-auth` errors keep their code and `extensions.http` but the HTTP status of an execution error stays
66
+ 200 under `application/graphql-response+json`.
67
+
68
+ ## `@defer`, `@stream` and subscriptions
69
+
70
+ Envelop done-hooks receive an async iterable for incremental results, as in Envelop on graphql 17. `onNext` runs per
71
+ payload (each `@defer` payload over `multipart/mixed` and SSE), `onEnd` once when the stream ends, including when the client
72
+ leaves. Subscriptions use `onSubscribeResult` the same way, and `onSubscribeError` can `setError`. It wraps only errors thrown while iterating the stream; errors of the initial
73
+ subscribe go through core's error handling.
74
+
75
+ ## Migrating from graphql-yoga
76
+
77
+ 1. Move every Envelop plugin from `createYoga({ plugins })` into `fromEnvelop([...])`.
78
+ 2. Yoga's own plugins (`onRequest`, `onResultProcess`, ...) are refused: replace them with `definePlugin` from `@graxia/core`.
79
+ 3. Pass the schema to `createGraxia({ schema })`; `useSchema` and `setSchema` are not needed.
80
+ 4. CORS, GraphiQL and persisted operations have graxia options of their own (`trustedDocuments`, `@graxia/graphiql`).
81
+
82
+ ## Tested plugins
83
+
84
+ All of them run on graphql 17.1 over a real server in this package's specs.
85
+
86
+ | Plugin | Result |
87
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
88
+ | `@envelop/depth-limit` 8.0.1 | Runs. A too-deep query answers 400. |
89
+ | `@envelop/generic-auth` 12.0.1 | Runs in `protect-all`, `protect-granular` and `resolve-only`. Type the user with `fromEnvelop<{ currentUser: User }>`. |
90
+ | `@envelop/response-cache` 10.0.1 | Runs: hits, invalidation by mutation, per-session entries. Needs a request on the context, which graxia provides. Not for `File` arguments, see below. |
91
+ | `@envelop/persisted-operations` 11.0.1 | Runs when the client also sends a placeholder `query` (core rejects a request without one first). Prefer core's `trustedDocuments`. |
92
+
93
+ ### response-cache and `File` variables
94
+
95
+ `@envelop/response-cache` keys an entry on the query and a hash of the variables, and a `File` serialises as `{}`.
96
+ With uploads on, a query that takes a `File` would answer the first cached result for every file, and, with
97
+ `session: () => null`, for every user. Do not cache operations with `File` arguments: make `enabled` return `false` for them (it receives the context, whose
98
+ `params` hold the operation), or use `shouldCacheResult` or `ignoredTypes`. A spec in this package pins the hazard (two
99
+ different files, the same answer) and the `enabled` fix (the resolver runs twice).
@@ -0,0 +1,22 @@
1
+ # Roadmap
2
+
3
+ Where `@graxia/envelop` is going, as what you get. A direction, not a commitment.
4
+
5
+ ## Later
6
+
7
+ - **Envelop context identity** — keep one context object across the hooks of an operation, so `@policy` of
8
+ `@envelop/generic-auth` can work.
9
+ - **Access to `serverContext`** in the Envelop context.
10
+ - **More specs** — `onSubscribeError` `setError` and `@stream` ([#100](https://github.com/softistx/graxia/issues/100)).
11
+
12
+ ## Not planned
13
+
14
+ - graphql-yoga plugins; graxia's own plugins replace them.
15
+ - Envelop `instrumentation`; use graxia's telemetry.
16
+
17
+ ## Shipped
18
+
19
+ ### 0.1.0
20
+
21
+ - **`fromEnvelop(plugins)`** — built and tested with `@envelop/depth-limit`, `@envelop/generic-auth`,
22
+ `@envelop/response-cache` and `@envelop/persisted-operations` on graphql 17.
@@ -0,0 +1,47 @@
1
+ # Troubleshooting
2
+
3
+ The errors a consumer can hit, headed by the message as it appears. All are a `GraxiaConfigError` thrown by `fromEnvelop`
4
+ at boot, unless said otherwise. Every message starts with `fromEnvelop: envelop plugin N of M (hooks)` or
5
+ `fromEnvelop: entry N of M`; the headings below match from the verb on.
6
+
7
+ ## entry N of M is X, not an Envelop plugin object
8
+
9
+ `fromEnvelop` was given a string, number or other non-object. Pass a plugin such as `useDepthLimit({ maxDepth: 10 })`, or a
10
+ falsy value (`cond && usePlugin()`) to skip one.
11
+
12
+ ## uses "instrumentation", which graxia cannot run
13
+
14
+ An Envelop plugin carries `instrumentation`. Remove it, or use `createGraxia({ telemetry })` or a graxia plugin
15
+ (`definePlugin`) instead.
16
+
17
+ ## uses "onRequest": this is a graphql-yoga plugin, not an Envelop one
18
+
19
+ A plugin uses a graphql-yoga hook (`onRequest`, `onRequestParse`, `onParams`, `onResultProcess`, `onResponse`,
20
+ `onYogaInit`, `onExecutionResult`). They belong to the HTTP layer graxia replaces: rewrite the plugin with `definePlugin`
21
+ from `@graxia/core`.
22
+
23
+ ## uses "onXxx", which is not an Envelop hook graxia knows
24
+
25
+ The hook name is misspelt or not an Envelop hook. Check the spelling, or write it as a graxia plugin.
26
+
27
+ ## calls setSchema, which graxia does not honour
28
+
29
+ An Envelop plugin tried `setSchema`. Pass the schema to `createGraxia({ schema })` (`useSchema` is not needed).
30
+
31
+ ## calls replaceSchema, which graxia does not honour
32
+
33
+ Raised while `graxia.ready` resolves: an instance serves the one schema it was created with. Pass the schema to
34
+ `createGraxia({ schema })`.
35
+
36
+ ## calls replaceParseResult, which graxia does not honour
37
+
38
+ Use `setParsedDocument` in `onParse`, or throw a `GraphQLError` there.
39
+
40
+ ## calls setResult in the after-hook of onValidate, which graxia does not honour
41
+
42
+ Call `setResult` in `onValidate` itself, or write a graxia plugin that replaces the errors.
43
+
44
+ ## Must provide a query string.
45
+
46
+ This is not a `GraxiaConfigError` but an HTTP 400 response. A persisted-operations request with an id and no `query` is refused by core before any plugin runs. Send a placeholder
47
+ `query` with the id, or use core's `trustedDocuments` with `documentId`.
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
- "name": "@graxia/envelop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@graxia/envelop",
3
+ "version": "0.1.0",
4
+ "description": "Run Envelop plugins inside graxia with one adapter",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "docs",
12
+ "README.md",
13
+ "package.json",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "keywords": [
25
+ "graphql",
26
+ "envelop",
27
+ "bun"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/softistx/graxia.git",
32
+ "directory": "packages/envelop"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "build": "bun run ../../build.ts",
39
+ "test": "bun test --pass-with-no-tests src",
40
+ "typecheck": "bun check"
41
+ },
42
+ "nxgt": {
43
+ "entrypoints": [
44
+ "src/index.ts"
45
+ ]
46
+ },
47
+ "devDependencies": {
48
+ "@envelop/core": "6.0.1",
49
+ "@envelop/depth-limit": "8.0.1",
50
+ "@envelop/generic-auth": "12.0.1",
51
+ "@envelop/persisted-operations": "11.0.1",
52
+ "@envelop/response-cache": "10.0.1",
53
+ "@graphql-hive/logger": "1.2.0",
54
+ "@graxia/core": "^0.6.0",
55
+ "@types/bun": "^1.4.4",
56
+ "graphql": "17.1.0"
57
+ },
58
+ "peerDependencies": {
59
+ "@envelop/core": "^5.6.1 || ^6.0.1",
60
+ "@graxia/core": "^0.6.0",
61
+ "graphql": "^17.1.0",
62
+ "typescript": "^6.0.3 || ^7.0.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "typescript": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "engines": {
70
+ "bun": ">=1.4.4"
71
+ }
72
+ }