@simtlix/simfinity-descriptor 0.0.0-stage → 3.15.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @simtlix/simfinity-descriptor
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
+ Optional schema-owned JSON client metadata for Simfinity. Depends on the exact
4
+ matching version of `@simtlix/simfinity-core`; supports both database facades.
5
+ Available since 3.15.0. Install it
6
+ as a direct application dependency at the version of your Simfinity runtime.
7
+
8
+ ```javascript
9
+ import { buildClientDescriptor, createClientDescriptorHandler } from '@simtlix/simfinity-descriptor';
10
+ const descriptor = buildClientDescriptor(schema);
11
+ app.all('/graphql-metadata', createClientDescriptorHandler(schema, { authorize: 'public' }));
12
+ ```
13
+
14
+ The application supplies its exact `createSchema()` result and explicitly chooses
15
+ public access or an authorization function. Importing this package does not patch
16
+ GraphQL introspection. See the [client descriptor guide](https://simtlix.github.io/simfinity.js/reference/client-descriptor.html)
17
+ for gated access, root input hints, early opt-out and client migration limits.
18
+
19
+ `rootInputUsage` reports whether a field is required or optional in the actual
20
+ generated root add/update input. Nested collection inputs can omit the inverse
21
+ reference supplied by their parent. Descriptors do not serialize arbitrary
22
+ validators or determine dynamic permissions. Finish declarations before the first
23
+ build; create a new schema and handler for metadata changes. Clones and composed
24
+ schemas do not inherit ownership.
25
+
26
+ Core remains dependency-free; structural HTTP declarations need no Node ambient
27
+ types. Directly importing `@simtlix/simfinity-core/introspection` requires core as
28
+ a direct dependency pinned to the facade's version. The 3.x introspection default
29
+ remains enabled, and clients selecting `__Field.extensions` must migrate before
30
+ using the early opt-out.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@simtlix/simfinity-descriptor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.15.0",
4
+ "description": "Schema-owned client metadata and an explicitly authorized HTTP endpoint for Simfinity",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./types/index.d.ts",
11
+ "default": "./src/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "src",
16
+ "types",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18.18.0"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/simtlix/simfinity.js",
27
+ "directory": "packages/descriptor"
28
+ },
29
+ "dependencies": {
30
+ "@simtlix/simfinity-core": "3.15.0"
31
+ },
32
+ "peerDependencies": {
33
+ "graphql": "^16.11.0"
34
+ },
35
+ "keywords": [
36
+ "simfinity",
37
+ "graphql",
38
+ "metadata",
39
+ "descriptor"
40
+ ]
41
+ }
@@ -0,0 +1,212 @@
1
+ import {
2
+ astFromValue, getNamedType, isEnumType, isInputObjectType, isInterfaceType, isNonNullType,
3
+ isObjectType, isScalarType, isUnionType, print,
4
+ } from 'graphql';
5
+ import SimfinityError from '@simtlix/simfinity-core/internal/errors';
6
+ import { schemaRegistrations } from '@simtlix/simfinity-core/internal/schema-registrations';
7
+ import { getFieldStorageName, getListShape, isVirtualField, normalizeConnectionField, virtualFieldOptions } from '@simtlix/simfinity-core/internal/relation-storage';
8
+ import { packageInfo } from './package-info.js';
9
+
10
+ // Exact schema ownership. No global adoption or field-name inference across module instances.
11
+ const snapshots = new WeakMap();
12
+ const textOrNull = (value) => (typeof value === 'string' ? value : null);
13
+ const descriptionOf = (value) => ({ description: textOrNull(value.description) });
14
+ const deprecated = (value) => (value.deprecationReason == null ? {} : { deprecationReason: textOrNull(value.deprecationReason) });
15
+ const mapOf = (entries) => Object.fromEntries(entries);
16
+ const sortedMap = (entries) => mapOf([...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
17
+ const freeze = (value) => {
18
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
19
+ Object.values(value).forEach(freeze);
20
+ Object.freeze(value);
21
+ }
22
+ return value;
23
+ };
24
+
25
+ const scalarBase = (type) => {
26
+ if (!type.baseScalarType) return null;
27
+ const seen = new Set([type]);
28
+ let base = type.baseScalarType;
29
+ while (base && !seen.has(base)) {
30
+ seen.add(base);
31
+ if (!base.baseScalarType) return textOrNull(base.name);
32
+ base = base.baseScalarType;
33
+ }
34
+ return null;
35
+ };
36
+
37
+ const collectTypes = (schema) => {
38
+ const found = new Map();
39
+ const pending = [schema.getQueryType(), schema.getMutationType()];
40
+ while (pending.length) {
41
+ const type = getNamedType(pending.pop());
42
+ if (!type || found.has(type.name)) continue;
43
+ found.set(type.name, type);
44
+ if (isUnionType(type)) pending.push(...type.getTypes());
45
+ if (isInterfaceType(type)) pending.push(...schema.getPossibleTypes(type));
46
+ if (isObjectType(type) || isInterfaceType(type)) pending.push(...type.getInterfaces());
47
+ if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {
48
+ for (const field of Object.values(type.getFields())) {
49
+ pending.push(field.type, ...(field.args || []).map((arg) => arg.type));
50
+ }
51
+ }
52
+ }
53
+ return found;
54
+ };
55
+
56
+ // A collection can name the child's GraphQL member or its stored alias. Never invent a private link.
57
+ const inverseOfCollection = (child, connectionField) => {
58
+ if (!isObjectType(child) || !connectionField) return null;
59
+ const normalized = normalizeConnectionField(child, connectionField).graphqlFieldName;
60
+ const matches = Object.entries(child.getFields()).filter(([name, field]) => (
61
+ name === connectionField || getFieldStorageName(name, field) === connectionField
62
+ ));
63
+ return matches.length === 1 ? normalized : null;
64
+ };
65
+ const relationOf = (owner, field) => {
66
+ const relation = field.extensions?.relation;
67
+ const target = getNamedType(field.type);
68
+ if (!relation || !isObjectType(target)) return null;
69
+ const collection = getListShape(field.type);
70
+ let inverseField = null;
71
+ if (!relation.embedded) {
72
+ if (collection) inverseField = inverseOfCollection(target, relation.connectionField);
73
+ else {
74
+ const matches = Object.entries(target.getFields()).filter(([, candidate]) => (
75
+ !candidate.extensions?.relation?.embedded && candidate.extensions?.relation
76
+ && getListShape(candidate.type)?.itemType === owner
77
+ && inverseOfCollection(owner, candidate.extensions.relation.connectionField) === field.name
78
+ ));
79
+ if (matches.length === 1) [inverseField] = matches[0];
80
+ }
81
+ }
82
+ return {
83
+ target: target.name, embedded: !!relation.embedded,
84
+ connectionField: textOrNull(relation.connectionField), displayField: textOrNull(relation.displayField), inverseField,
85
+ };
86
+ };
87
+ const fieldKind = (field, relation) => {
88
+ const named = getNamedType(field.type);
89
+ if (relation) return relation.embedded ? 'embedded' : getListShape(field.type) ? 'collection' : 'reference';
90
+ if (isScalarType(named)) return 'scalar';
91
+ if (isEnumType(named)) return 'enum';
92
+ if (isInterfaceType(named)) return 'interface';
93
+ if (isUnionType(named)) return 'union';
94
+ return 'object';
95
+ };
96
+
97
+ const createDescriptor = (schema, registrations) => {
98
+ const types = collectTypes(schema);
99
+ const registered = new Map(registrations.map((entry) => [entry.gqltype, entry]));
100
+ const defaults = [];
101
+ const inputValues = new Map();
102
+ const input = (field) => {
103
+ if (inputValues.has(field)) return inputValues.get(field);
104
+ const result = { name: field.name, type: String(field.type), ...descriptionOf(field), ...deprecated(field), hasDefault: field.defaultValue !== undefined };
105
+ // Do not invoke application scalar serializers during createSchema(). Keep these references only
106
+ // until the first explicit descriptor build, then release them. Nothing executable enters JSON.
107
+ inputValues.set(field, result);
108
+ if (result.hasDefault) defaults.push({ target: result, type: field.type, value: field.defaultValue });
109
+ return result;
110
+ };
111
+ const operation = (field) => ({ args: field.args.map(input), returns: String(field.type), ...descriptionOf(field), ...deprecated(field) });
112
+ const queryEntries = Object.entries(schema.getQueryType()?.getFields() || {}).map(([name, field]) => {
113
+ const registration = registrations.find((entry) => entry.endpoint
114
+ && entry.simpleEntityEndpointName === name && field.type === entry.gqltype);
115
+ const marker = field.extensions?.simfinityQuery;
116
+ const kind = registration ? 'get' : marker?.operation === 'find' ? 'list' : marker?.operation === 'aggregate' ? 'aggregate' : 'customQuery';
117
+ return [name, { ...operation(field), type: registration?.gqltype.name || (kind !== 'customQuery' ? marker.typeName : null), operation: kind,
118
+ ...(marker?.view ? { view: marker.view.name } : {}) }];
119
+ });
120
+ const mutationKinds = { save: 'add', update: 'update', delete: 'delete', state_changed: 'transition', custom_mutation: 'customMutation' };
121
+ const mutationEntries = Object.entries(schema.getMutationType()?.getFields() || {}).map(([name, field]) => {
122
+ const marker = field.extensions?.simfinityMutation;
123
+ const kind = mutationKinds[marker?.operation] || 'customMutation';
124
+ const result = { ...operation(field), type: marker?.typeName || null, operation: kind };
125
+ if (['add', 'update', 'delete'].includes(kind) && result.description === kind) result.description = null;
126
+ if (kind === 'transition') Object.assign(result, { action: marker.action, from: textOrNull(marker.from), to: textOrNull(marker.to) });
127
+ return [name, result];
128
+ });
129
+ const operations = { query: sortedMap(queryEntries), mutation: sortedMap(mutationEntries) };
130
+ const typeEntries = [...types].map(([name, type]) => {
131
+ const entry = registered.get(type);
132
+ let kind = 'object';
133
+ if (isInputObjectType(type)) kind = 'input';
134
+ else if (isScalarType(type)) kind = 'scalar';
135
+ else if (isEnumType(type)) kind = 'enum';
136
+ else if (isInterfaceType(type)) kind = 'interface';
137
+ else if (isUnionType(type)) kind = 'union';
138
+ const associated = [...queryEntries, ...mutationEntries].filter(([, op]) => op.type === name);
139
+ if (entry?.endpoint && associated.length) kind = 'entity';
140
+ const result = { kind, ...descriptionOf(type) };
141
+ if (kind === 'entity') {
142
+ result.endpoints = mapOf(associated.filter(([, op]) => !op.view && ['get', 'list', 'aggregate', 'add', 'update', 'delete'].includes(op.operation)).map(([key, op]) => [op.operation, key]));
143
+ }
144
+ const rootInputs = ['add', 'update'].flatMap((operation) => {
145
+ const endpoint = result.endpoints?.[operation];
146
+ const root = endpoint && schema.getMutationType().getFields()[endpoint];
147
+ const inputType = root && getNamedType(root.args.find((arg) => arg.name === 'input')?.type);
148
+ return isInputObjectType(inputType) ? [[operation, inputType.getFields()]] : [];
149
+ });
150
+ if (entry) {
151
+ const inputs = Object.entries({ add: entry.inputType, update: entry.updateInputType })
152
+ .filter(([, item]) => item && types.get(item.name) === item).map(([key, item]) => [key, item.name]);
153
+ if (inputs.length) result.inputs = mapOf(inputs);
154
+ if (kind === 'entity') {
155
+ const state = type.getFields().state;
156
+ const enumType = state && getNamedType(state.type);
157
+ result.stateMachine = entry.stateMachine && isEnumType(enumType) ? {
158
+ field: 'state', enum: enumType.name, initialState: textOrNull(entry.stateMachine.initialState?.name),
159
+ states: enumType.getValues().map((value) => value.name),
160
+ actions: mutationEntries.filter(([, op]) => op.type === name && op.operation === 'transition').map(([mutation, op]) => ({ name: op.action, mutation, description: op.description, from: op.from, to: op.to })),
161
+ } : null;
162
+ }
163
+ }
164
+ if (isInputObjectType(type)) result.fields = Object.values(type.getFields()).map(input);
165
+ else if (isObjectType(type) || isInterfaceType(type)) {
166
+ result.interfaces = type.getInterfaces().map((item) => item.name);
167
+ result.fields = Object.values(type.getFields()).map((field) => {
168
+ const relation = relationOf(type, field);
169
+ const virtual = virtualFieldOptions(field);
170
+ return {
171
+ name: field.name, type: String(field.type), kind: fieldKind(field, relation), ...descriptionOf(field), ...deprecated(field),
172
+ readOnly: !!field.extensions?.readOnly || !!virtual, unique: field.extensions?.unique === true,
173
+ stateMachine: !!entry?.stateMachine && field.name === 'state' && !field.extensions?.readOnly,
174
+ ...(relation ? { relation } : {}), ...(virtual ? { virtual } : {}),
175
+ ...(entry ? { queryable: !isVirtualField(field) && entry.queryableFields[field.name] } : {}),
176
+ ...(rootInputs.length ? { rootInputUsage: mapOf(rootInputs.flatMap(([operation, fields]) => {
177
+ const inputField = fields[field.name];
178
+ return inputField ? [[operation, isNonNullType(inputField.type) && inputField.defaultValue === undefined ? 'required' : 'optional']] : [];
179
+ })) } : {}),
180
+ ...(field.args.length ? { args: field.args.map(input) } : {}),
181
+ };
182
+ });
183
+ }
184
+ if (isInterfaceType(type)) result.possibleTypes = schema.getPossibleTypes(type).map((item) => item.name);
185
+ if (isUnionType(type)) result.possibleTypes = type.getTypes().map((item) => item.name);
186
+ if (isEnumType(type)) result.values = type.getValues().map((item) => ({ name: item.name, ...descriptionOf(item), deprecationReason: textOrNull(item.deprecationReason) }));
187
+ if (isScalarType(type)) result.baseScalar = scalarBase(type);
188
+ return [name, result];
189
+ });
190
+ snapshots.set(schema, { document: { formatVersion: 1, generator: packageInfo,
191
+ roots: { query: schema.getQueryType()?.name || null, mutation: schema.getMutationType()?.name || null },
192
+ operations, types: sortedMap(typeEntries) }, defaults });
193
+ };
194
+
195
+ export const buildClientDescriptor = (schema) => {
196
+ const registrations = schemaRegistrations(schema);
197
+ if (!registrations) throw new SimfinityError('Expected a Simfinity schema returned by this core installation', 'NOT_A_SIMFINITY_SCHEMA', 500);
198
+ if (!snapshots.has(schema)) createDescriptor(schema, registrations);
199
+ const snapshot = snapshots.get(schema);
200
+ if (snapshot.defaults) {
201
+ const pending = snapshot.defaults;
202
+ snapshot.defaults = null;
203
+ for (const { target, type, value } of pending) {
204
+ try {
205
+ const ast = astFromValue(value, type);
206
+ if (ast) target.defaultValue = print(ast);
207
+ } catch { /* Opaque custom scalar defaults are deliberately omitted. */ }
208
+ }
209
+ freeze(snapshot.document);
210
+ }
211
+ return snapshot.document;
212
+ };
package/src/http.js ADDED
@@ -0,0 +1,71 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { buildClientDescriptor } from './client-descriptor.js';
3
+ import SimfinityError from '@simtlix/simfinity-core/internal/errors';
4
+
5
+ const canonical = (value) => {
6
+ if (Array.isArray(value)) return value.map(canonical);
7
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
8
+ return value;
9
+ };
10
+ const invalid = () => new SimfinityError('Invalid client descriptor handler options: provide authorize: public or a function, and optional context/onError', 'INVALID_CLIENT_DESCRIPTOR_OPTIONS', 500);
11
+ const KEYS = new Set(['authorize', 'context', 'onError']);
12
+ const readOptions = (options) => {
13
+ if (!options || ![Object.prototype, null].includes(Object.getPrototypeOf(options))
14
+ || Reflect.ownKeys(options).some((key) => !KEYS.has(key))
15
+ || !Object.hasOwn(options, 'authorize')
16
+ || (options.authorize !== 'public' && typeof options.authorize !== 'function')
17
+ || (options.onError !== undefined && typeof options.onError !== 'function')) throw invalid();
18
+ return { authorize: options.authorize, context: options.context, onError: options.onError };
19
+ };
20
+ // Validate the whole list, including quoted commas; an arbitrary substring is not a cache match.
21
+ const matches = (header, etag) => {
22
+ if (typeof header !== 'string') return false;
23
+ const value = header.trim();
24
+ if (value === '*') return true;
25
+ if (!/^(?:W\/)?"[\x21\x23-\x7e\x80-\xff]*"(?:\s*,\s*(?:W\/)?"[\x21\x23-\x7e\x80-\xff]*")*$/.test(value)) return false;
26
+ return [...value.matchAll(/(?:W\/)?"[\x21\x23-\x7e\x80-\xff]*"/g)].some(([tag]) => tag.replace(/^W\//, '') === etag);
27
+ };
28
+ const envelope = (message, code) => JSON.stringify({ errors: [{ message, extensions: { code } }] });
29
+
30
+ /** A separately mounted, immutable descriptor. Authorization runs on HEAD and cache hits too. */
31
+ export const createClientDescriptorHandler = (schema, options) => {
32
+ const { authorize, context, onError } = readOptions(options);
33
+ const body = JSON.stringify(canonical(buildClientDescriptor(schema)));
34
+ const etag = `"${createHash('sha256').update(body).digest('hex')}"`;
35
+ const gated = authorize !== 'public';
36
+ return async (req, res) => {
37
+ const send = (status, content) => {
38
+ res.statusCode = status;
39
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
40
+ res.end(req.method === 'HEAD' ? undefined : content);
41
+ };
42
+ try {
43
+ if (!['GET', 'HEAD'].includes(req.method)) {
44
+ res.setHeader('Allow', 'GET, HEAD');
45
+ res.setHeader('Cache-Control', 'no-store');
46
+ send(405, envelope('Method not allowed', 'METHOD_NOT_ALLOWED'));
47
+ return;
48
+ }
49
+ const ctx = typeof context === 'function' ? await context(req) : context;
50
+ if (gated) {
51
+ const allowed = await authorize(req, ctx);
52
+ if (allowed !== true && allowed !== undefined) throw new SimfinityError('Access denied', 'FORBIDDEN', 403);
53
+ }
54
+ res.setHeader('Cache-Control', gated ? 'private, no-cache' : 'no-cache');
55
+ if (gated) res.setHeader('Vary', 'Authorization, Cookie');
56
+ res.setHeader('ETag', etag);
57
+ if (matches(req.headers['if-none-match'], etag)) {
58
+ res.statusCode = 304;
59
+ res.end();
60
+ } else send(200, body);
61
+ } catch (error) {
62
+ const known = error instanceof SimfinityError && [401, 403].includes(error.getStatus());
63
+ try { if (!known && onError) await onError(error, req, res); } catch { /* Reporting cannot replace the HTTP result. */ }
64
+ if (res.headersSent || res.writableEnded || res.destroyed) return;
65
+ res.removeHeader('ETag');
66
+ res.setHeader('Cache-Control', 'no-store');
67
+ send(known ? error.getStatus() : 500,
68
+ envelope(known ? error.message : 'Internal server error', known ? error.getCode() : 'INTERNAL_SERVER_ERROR'));
69
+ }
70
+ };
71
+ };
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { buildClientDescriptor } from './client-descriptor.js';
2
+ export { createClientDescriptorHandler } from './http.js';
@@ -0,0 +1,2 @@
1
+ // Generated by scripts/release-packages.js; keeps the descriptor builder free of Node/JSON loader dependencies.
2
+ export const packageInfo = Object.freeze({ name: '@simtlix/simfinity-descriptor', version: '3.15.0' });
@@ -0,0 +1,96 @@
1
+ import type { GraphQLSchema } from 'graphql';
2
+
3
+ export interface ClientDescriptorInputValue {
4
+ readonly name: string;
5
+ readonly type: string;
6
+ readonly description: string | null;
7
+ readonly deprecationReason?: string | null;
8
+ readonly hasDefault: boolean;
9
+ /** External GraphQL literal; omitted for unrepresentable custom defaults. */
10
+ readonly defaultValue?: string;
11
+ }
12
+ export interface ClientDescriptorRelation {
13
+ readonly target: string;
14
+ readonly embedded: boolean;
15
+ readonly connectionField: string | null;
16
+ readonly displayField: string | null;
17
+ readonly inverseField: string | null;
18
+ }
19
+ export interface ClientDescriptorField {
20
+ readonly name: string;
21
+ readonly type: string;
22
+ readonly kind: 'scalar' | 'enum' | 'embedded' | 'reference' | 'collection' | 'object' | 'interface' | 'union';
23
+ readonly description: string | null;
24
+ readonly deprecationReason?: string | null;
25
+ readonly readOnly: boolean;
26
+ readonly unique: boolean;
27
+ readonly stateMachine: boolean;
28
+ readonly queryable?: boolean;
29
+ /** Usage in this schema's generated root add/update inputs, not permissions or nested inputs. */
30
+ readonly rootInputUsage?: Readonly<{ add?: 'required' | 'optional'; update?: 'required' | 'optional' }>;
31
+ readonly virtual?: Readonly<{ mcp: 'tool' | 'select' | false }>;
32
+ readonly relation?: ClientDescriptorRelation;
33
+ readonly args?: readonly ClientDescriptorInputValue[];
34
+ }
35
+ export interface ClientDescriptorOperation {
36
+ readonly type: string | null;
37
+ readonly operation: 'get' | 'list' | 'aggregate' | 'add' | 'update' | 'delete' | 'transition' | 'customQuery' | 'customMutation';
38
+ readonly args: readonly ClientDescriptorInputValue[];
39
+ readonly returns: string;
40
+ readonly description: string | null;
41
+ readonly deprecationReason?: string | null;
42
+ readonly view?: string;
43
+ readonly action?: string;
44
+ readonly from?: string | null;
45
+ readonly to?: string | null;
46
+ }
47
+ export interface ClientDescriptorStateMachine {
48
+ readonly field: 'state';
49
+ readonly enum: string;
50
+ readonly initialState: string | null;
51
+ readonly states: readonly string[];
52
+ readonly actions: readonly Readonly<{ name: string; mutation: string; description: string | null; from: string | null; to: string | null }>[];
53
+ }
54
+ export interface ClientDescriptorType {
55
+ readonly kind: 'entity' | 'object' | 'interface' | 'union' | 'input' | 'enum' | 'scalar';
56
+ readonly description: string | null;
57
+ readonly endpoints?: Readonly<Partial<Record<'get' | 'list' | 'aggregate' | 'add' | 'update' | 'delete', string>>>;
58
+ readonly inputs?: Readonly<{ add?: string; update?: string }>;
59
+ readonly stateMachine?: ClientDescriptorStateMachine | null;
60
+ readonly fields?: readonly (ClientDescriptorField | ClientDescriptorInputValue)[];
61
+ readonly interfaces?: readonly string[];
62
+ readonly possibleTypes?: readonly string[];
63
+ readonly values?: readonly Readonly<{ name: string; description: string | null; deprecationReason: string | null }>[];
64
+ readonly baseScalar?: string | null;
65
+ }
66
+ export interface ClientDescriptor {
67
+ readonly formatVersion: 1;
68
+ readonly generator: Readonly<{ name: '@simtlix/simfinity-descriptor'; version: string }>;
69
+ readonly roots: Readonly<{ query: string | null; mutation: string | null }>;
70
+ readonly types: Readonly<Record<string, ClientDescriptorType>>;
71
+ readonly operations: Readonly<{ query: Readonly<Record<string, ClientDescriptorOperation>>; mutation: Readonly<Record<string, ClientDescriptorOperation>> }>;
72
+ }
73
+ /** Immutable metadata of this exact createSchema result; rejects transformed/foreign schemas. */
74
+ export function buildClientDescriptor(schema: GraphQLSchema): ClientDescriptor;
75
+
76
+ /** Minimal structural Node/Express request; no Node ambient types are required. */
77
+ export interface DescriptorRequest {
78
+ method?: string | undefined;
79
+ headers: Readonly<Record<string, string | readonly string[] | undefined>>;
80
+ }
81
+ export interface DescriptorResponse {
82
+ statusCode: number;
83
+ readonly headersSent?: boolean;
84
+ readonly writableEnded?: boolean;
85
+ readonly destroyed?: boolean;
86
+ setHeader(name: string, value: string): unknown;
87
+ removeHeader(name: string): void;
88
+ end(body?: string): unknown;
89
+ }
90
+ export interface ClientDescriptorHandlerOptions<Context = unknown> {
91
+ authorize: 'public' | ((req: DescriptorRequest, context: Context) => boolean | void | Promise<boolean | void>);
92
+ context?: Context | ((req: DescriptorRequest) => Context | Promise<Context>);
93
+ /** Reports unexpected failures, not expected 401/403 denials. */
94
+ onError?: (error: unknown, req: DescriptorRequest, res: DescriptorResponse) => void | Promise<void>;
95
+ }
96
+ export function createClientDescriptorHandler<Context = unknown>(schema: GraphQLSchema, options: ClientDescriptorHandlerOptions<Context>): (req: DescriptorRequest, res: DescriptorResponse) => Promise<void>;