@simtlix/simfinity-core 3.9.0 → 3.11.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/README.md CHANGED
@@ -8,19 +8,20 @@ For relational storage, `@simtlix/simfinity-sql` builds on core and delegates ph
8
8
 
9
9
  ## Runtime
10
10
 
11
- `createRuntime(adapter)` creates a Simfinity runtime. Each instance owns its registrations, generated input types, middleware, scopes, hooks, custom mutations, and state machines; the GraphQL type objects it builds resolvers for are bound to it, and query and mutation limits are process-wide. It exposes:
11
+ `createRuntime(adapter)` creates a Simfinity runtime. Each instance owns its registrations, generated input types, middleware, scopes, hooks, custom queries and mutations, and state machines; the GraphQL type objects it builds resolvers for are bound to it, and query and mutation limits are process-wide. It exposes:
12
12
 
13
13
  - `connect`, `addNoEndpointType`, and `createSchema` for registration and schema creation;
14
14
  - `getModel`, `getType`, `getInputType`, and `getRegistrations` for runtime inspection;
15
15
  - `use`, `registerMutation`, and `saveObject` for middleware and write orchestration;
16
+ - `registerCustomQuery` for reads whose results are not stored records, such as previews, other sources or permission evaluations;
16
17
  - `preventCreatingCollection` to pass validation-only storage setup to an adapter;
17
- - `configureQueryLimits` and `configureMutationLimits` for the process-wide page-size and nested-operation limits.
18
+ - `configureQueryLimits` and `configureMutationLimits` for the process-wide page-size, reference-frame and nested-operation limits.
18
19
 
19
20
  The adapter supplies model creation, identifiers, transactions, record reads and writes, queries, counts, aggregations, and inverse collection reads. `DatabaseAdapter`, `Runtime`, controller, middleware, registration, and state-machine interfaces are exported in the TypeScript declarations. A runtime binds one adapter; create another runtime to use another database or configuration. The GraphQL types that `prepare()` and `createModel()` receive still contain virtual fields, which must never be stored: an adapter that builds storage from a type's fields skips each field for which `isVirtualField(field)`, exported by this package with `virtualFieldOptions(field)`, returns true, on entities and embedded types alike, or builds it from `describeModels()`, which leaves them out. Generated writes, filters, sorts and aggregations never name a virtual field, but a controller hook can still assign one. An adapter can also define `getByIds(model, ids, { context })`, which returns the records it finds in `getById` shape and any order; the runtime then batches generated single-reference reads per request and type, matching records by `castId`, splitting batches at `maxPageSize`, and reading an ID with `getById` when a batch read fails or when `castId` would normalize or reject it. `castId` should throw a `NOT_VALID_ID` (400) `SimfinityError` for a malformed value and must not create a new identifier. An adapter can define `readByIdIsInert(model)`, returning `true` when a `getById` of that model has no side effects and `update()` and `delete()` reject the same malformed IDs with `NOT_VALID_ID` (400) and return null for a missing record; the runtime then skips the reads before deletes without an `onDelete` hook and before updates that merge no embedded value and have neither `onUpdating` nor nested collection items. The SQL adapter always reports it, and the MongoDB adapter does for models without `find`, `findOne`, `findOneAndUpdate` or `findOneAndDelete` middleware and without application `_id` setters or overrides of the statics those reads and writes call. When `getById` rejects a stored reference value that way, including one that `castId` rejected first, the generated reference field fails with an `InternalServerError` (500), since the client did not send the value. `update()` resolves to the updated record as stored, or null; nested collection children of that record are linked to and checked against its `_id`, else `id`, else the requested ID. An adapter that hydrates records can define `readEmbeddedValue(value)`: every nullable, singular embedded object field without a resolver then passes its value through it, so an explicitly stored `null` reads as `null`. The field is read as graphql's default resolver reads it, so a method on the parent is called and a promise it returns is awaited before the hook receives the value. Simfinity then reads as `null` an object that holds no data when a required member would read as `null`, not counting `id`, `readOnly` and virtual members, interface and union members, members with an application resolver and referenced collections; runtimes that share the type read the same. It reads the stored members, never calling a getter, and counts a stored `_id` as `id`; it reads nothing from objects whose type has no member that counts, and an error while reading returns the object unchanged. An adapter whose hydrated records render members through getters can also define `rawEmbeddedValue(value)`, which returns a record's stored data as a plain object, or the record unchanged when that data does not show what it renders; a value that is not a plain object counts as data. The MongoDB adapter defines both.
20
21
 
21
22
  An adapter can also define `findChildrenBatch(model, type, connectionField, parentIds, args, { context })`, the batch form of `findChildren` for generated collection fields, and a synchronous `batchesChildren(model, type, connectionField)` predicate. The runtime calls both as adapter methods and checks them on every read. When the method is missing or the predicate returns `false`, each field calls `findChildren` at once with the arguments object it built, as before. Otherwise, within one request (a context object), the runtime groups the collection reads of one related type and connection storage field whose effective arguments (after middleware, the scope and joined scopes) hold the same plain data and are requested in the same tick, that is before the promise jobs queued so far have run. It calls the method with 2 to 100 distinct parent IDs, each a raw ID that `castId` accepts without changing its string form, and with a copy of the arguments that the method may change; a group with one distinct parent calls `findChildren`. Return one array per parent ID, in order, each holding exactly the records, order and page that `findChildren` returns for that parent; records should show their parent under the connection field, or not show one. Fields of one parent share its records, each with its own array. After a rejection, or a result of another shape or with records of another parent, each field reads alone with `findChildren`; failures other than a `SimfinityError`, and results of another shape, are logged once per type. Pairing rule: the batch must reproduce `this.findChildren`, so `batchesChildren` must return `false` when `this.findChildren` is not the adapter's own function, as with a spread copy or an `Object.assign` override that changes how children are read. The bundled adapters follow this rule: both define the two members only with `batchedCollections: true`: the SQL adapter when the schema is prepared and its plugin's `compileChildrenQuery` is paired with its `compileQuery`, and the MongoDB adapter at creation. To opt out on one adapter instance, set `adapter.findChildrenBatch = undefined` (deleting it does nothing for a class whose method is on the prototype), or make `batchesChildren` return `false`. A copy that overrides `getById` still inherits the base `getByIds`, as before.
22
23
 
23
- An adapter declares the filter operators it compiles as `queryFeatures: { operators }`, a list of `QLOperator` values that includes `EQ`, which a condition without an operator means; names this version does not know are ignored. `createRuntime()` reads it once and throws `INVALID_QUERY_FEATURES` (500) unless it is `undefined`, `null` or an object whose `operators` is an array of strings. Without a declaration the adapter supports the operators of 3.7.0, `EQ`, `NE`, `LT`, `LTE`, `GT`, `GTE`, `BTW`, `IN`, `NIN` and `LIKE`, so it never receives a text operator such as `ILIKE` that it would drop or misread. A list, count, aggregate or collection read, or a by-ID read through a `get_by_id` scope, that uses another `QLOperator` value fails with `UNSUPPORTED_QUERY` (400): the runtime checks the client's arguments before middleware runs and the final arguments, with what middleware, scopes and joined scopes added, before it calls the adapter. Operators that `QLOperator` does not list still reach the adapter. An adapter that receives the text operators must apply their rules: literal values, a `String` field or list, and `INVALID_FILTER_VALUE` (400) for a value that is not a string or contains U+0000. `createQueryPlan(models, entity, args, { operators })` validates them and rejects operators outside `operators` with `UNSUPPORTED_QUERY`.
24
+ An adapter declares the filter operators it compiles as `queryFeatures: { operators }`, a list of `QLOperator` values that includes `EQ`, which a condition without an operator means; names this version does not know are ignored. `createRuntime()` reads it once and throws `INVALID_QUERY_FEATURES` (500) unless it is `undefined`, `null` or an object whose `operators` is an array of strings and whose optional `referenceEmptiness` is a boolean, `undefined` or `null`. Without a declaration the adapter supports the operators of 3.7.0, `EQ`, `NE`, `LT`, `LTE`, `GT`, `GTE`, `BTW`, `IN`, `NIN` and `LIKE`, so it never receives a text operator such as `ILIKE`, or an emptiness operator, `IS_EMPTY` or `IS_NOT_EMPTY`, that it would drop or misread. A list, count, aggregate or collection read, or a by-ID read through a `get_by_id` scope, that uses another `QLOperator` value fails with `UNSUPPORTED_QUERY` (400): the runtime checks the client's arguments before middleware runs and the final arguments, with what middleware, scopes and joined scopes added, before it calls the adapter. Operators that `QLOperator` does not list still reach the adapter. An adapter that receives the text operators must apply their rules: literal values, a `String` field or list, and `INVALID_FILTER_VALUE` (400) for a value that is not a string or contains U+0000. `createQueryPlan(models, entity, args, { operators })` validates them and rejects operators outside `operators` with `UNSUPPORTED_QUERY`. An adapter that declares `IS_EMPTY` and `IS_NOT_EMPTY` must compile their semantics on the queried record's own fields, where `IS_NOT_EMPTY` is the exact complement of `IS_EMPTY`: a `String` is empty when missing, `null` or `""`, any other scalar or enum when missing or `null`, a list when missing, `null` or `[]`, and an embedded object when missing, `null` or every stored member is empty. The runtime rejects a value other than `null` and a path inside a list before it calls the adapter, and also emptiness through references and collections unless the adapter declares `referenceEmptiness: true`, so the adapter receives conditions whose `value` may be absent and whose term or group `path` may be omitted, `null` or `""` to name the field itself; `createQueryPlan` plans them as `{ kind: 'predicate', path, operator, value: null }`, whose `path` may end at a scalar list, an embedded list or an embedded object. See [empty values](https://simtlix.github.io/simfinity.js/guide/queries.html#empty-values). An adapter that declares `referenceEmptiness: true` also receives emptiness conditions whose path crosses single references and ends at a reference or a collection, and embedded objects with reference and collection members. A client's such term or group condition carries the key `__scope: { id, scopes }`, where `scopes` holds, for each reference it crosses and each reference, collection or member it ends at or reads, keyed by the dotted path from the queried record, the arguments that the target type's `find` scope produced, or `null` when it added nothing. The adapter must join a crossed reference only where that scope admits the target, and count at an end or member only the records that the scope admits, so that a record the caller may not see reads as a missing one, also on a later hop with a `null` scope; a condition without `__scope` comes from middleware or a scope and reads stored data. `createQueryPlan(models, entity, args, { operators, referenceEmptiness: true })` lifts each filled `__scope` into the predicate's `scopes`, planning each scope on its target type, and throws `DETACHED_CLIENT_FILTER` (500) for a `__scope` that lacks a path; its `referenceEmptiness` option defaults to `true` when `operators` is omitted and to `false` otherwise. See [references and collections](https://simtlix.github.io/simfinity.js/guide/queries.html#references-and-collections).
24
25
 
25
26
  Entity types, those registered with `connect()` and the targets of non-embedded relations, resolve `id` to `_id`, falling back to `id`, whatever the `createSchema()` allowlists include; types used only as embedded values keep their declared `id`. Embedded copies of an entity type resolve the same way, so they return their declared `id` unless the adapter stores an `_id` for them, as MongoDB does for embedded list items. The resolver is set on the type object, so it applies in every runtime that shares the type. `createSchema()` marks these registrations with `storedIdentity: true` before calling `adapter.prepare()`.
26
27
 
@@ -28,7 +29,7 @@ When a runtime first creates a schema, it binds each GraphQL object type whose n
28
29
 
29
30
  Registration and `createSchema()` validate `extensions.scope` (`INVALID_SCOPE`) and reject list or embedded relations to unregistered types (`UNREGISTERED_RELATION_TARGET`); `use()` rejects non-functions (`INVALID_MIDDLEWARE`). Before `adapter.prepare()`, `createSchema()` rejects a writable non-embedded list relation without a non-empty child `connectionField` whose resolver it would generate (`INVALID_MODEL`, 400). A collection without `connectionField` that has an application resolver, or is `readOnly`, only logs a `Configuration issue` warning, unless it is both, and nested writes through it fail with `INVALID_MODEL` (500) before anything is written; adapters that describe the whole model, such as PostgreSQL and transactional MongoDB, still reject it in `prepare()`. Fields named like generated query arguments (`sort`, `pagination`, `AND`, `OR`, and `aggregation` on aggregate endpoints) also log a warning once per runtime. Virtual fields (`extensions: { virtual: true }` or `{ virtual: { mcp: 'tool' | 'select' | false } }`, with the field's own `resolve`) are never stored, get no generated input and no filter argument, and resolve wherever their type appears; `createSchema()` rejects an invalid declaration, a virtual field without its own resolver or with `relation`, `unique: true`, `validations`, `queryable: true` or `readOnly: false`, and a virtual identity, index, state-machine `state` or `connectionField` field (`INVALID_MODEL`, 400). A client filter, sort, `groupId` or fact path through a virtual field fails with `FORBIDDEN_FILTER_PATH` (403), and one that middleware or a scope adds fails with `INVALID_MODEL` (500). A `readOnly` field with arguments and its own resolver that is not virtual, a reference or a collection logs a `Configuration issue` warning once per runtime. Generated inputs that would have no fields are left out with a `Configuration issue` warning, with the collection operations, embedded fields and mutations that would take them; a non-null embedded field whose embedded type has no writable fields throws `INVALID_MODEL` (400) when generated mutations reach its owner. An application type named `FieldExtensionsType` or `RelationType` makes Simfinity rename its introspection metadata types to `SimfinityFieldExtensionsType` and `SimfinityRelationType` when it is in the process's first Simfinity schema. That schema fixes the names: in a later `createSchema()`, an application type with one of the current names, the original ones or the fallback names after a rename, throws `RESERVED_TYPE_NAME` (500), before `adapter.prepare()` when it is an included endpoint type, a registered mutation's input or output type, an output type they reach or a field argument's type, and when the schema is constructed otherwise, such as for a type inside an input object's fields.
30
31
 
31
- Generated and custom mutations run through `adapter.withTransaction`. Retried attempts receive fresh clones of GraphQL input objects, lists, and dates while enum values keep their identity. An adapter can define `stateValue` when its persisted enum representation differs from GraphQL enum names.
32
+ Generated and custom mutations run through `adapter.withTransaction`. Retried attempts receive fresh clones of GraphQL input objects, lists, and dates while enum values keep their identity. Custom queries run without a transaction: their callback receives `(input, context)` and opens one through the engine's API when it needs it. `createSchema()` takes an optional fourth argument, an options object whose only key, `includedCustomQueries`, selects custom queries by name; any other value or key throws `INVALID_SCHEMA_OPTIONS` (500) before `adapter.prepare()`. A schema without mutation fields has no `Mutation` root. An adapter can define `stateValue` when its persisted enum representation differs from GraphQL enum names.
32
33
 
33
34
  Importing the runtime installs Simfinity's `__Field.extensions` introspection field once per GraphQL module instance; its `readOnly` flag reads `true` for virtual fields. Multiple runtimes and driver packages can be imported together without cloning schemas or duplicating introspection types.
34
35
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simtlix/simfinity-core",
3
- "version": "3.9.0",
3
+ "version": "3.11.0",
4
4
  "description": "Driver-free GraphQL runtime and model metadata for Simfinity",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/auth/index.js CHANGED
@@ -45,7 +45,7 @@ import {
45
45
  import SimfinityError from '../errors/simfinity.error.js';
46
46
  import { UnauthenticatedError, ForbiddenError, createAuthError } from './errors.js';
47
47
  import { isPolicyExpression, createRuleFromExpression, evaluateExpression } from './expressions.js';
48
- import { collectQueryPaths, walkQueryPath } from '../query-plan.js';
48
+ import { collectQueryPathEntries, walkQueryPath } from '../query-plan.js';
49
49
  import { relationFieldOwners } from '../relation-owners.js';
50
50
  import { isThenable } from './thenable.js';
51
51
  import {
@@ -246,13 +246,15 @@ const executeRule = async (rule, parent, args, ctx, info) => {
246
246
  * field's filter, sort and aggregation arguments. Each segment needs its own `Type.field` rule
247
247
  * (exact, wildcard, then default policy). Rules run without a parent, with empty args and the
248
248
  * path field's identity in info, so parent-dependent rules such as isOwner deny query paths. A rule that
249
- * throws anything other than a Simfinity or GraphQL error denies the path.
249
+ * throws anything other than a Simfinity or GraphQL error denies the path. An IS_EMPTY or IS_NOT_EMPTY
250
+ * condition on an embedded object reads its stored members, so each member path is authorized as a
251
+ * named path is, after it, with the same answer for a field that is both.
250
252
  */
251
253
  const authorizeQueryPaths = async (permissions, defaultPolicy, schema, query, args, ctx, info) => {
252
254
  const queriedType = query && schema?.getType?.(query.typeName);
253
255
  if (!queriedType) return;
254
256
  const checked = new Set();
255
- for (const segments of collectQueryPaths(args, query.operation)) {
257
+ for (const { segments } of collectQueryPathEntries(args, query.operation, { gqltype: queriedType, expandMembers: true })) {
256
258
  const steps = [];
257
259
  walkQueryPath(queriedType, segments, (step) => steps.push(step));
258
260
  for (const { type, fieldName, field } of steps) {
@@ -19,6 +19,8 @@ const QLOperator = new GraphQLEnumType({
19
19
  ENDS_WITH: { value: 'ENDS_WITH' },
20
20
  IENDS_WITH: { value: 'IENDS_WITH' },
21
21
  IEQ: { value: 'IEQ' },
22
+ IS_EMPTY: { value: 'IS_EMPTY' },
23
+ IS_NOT_EMPTY: { value: 'IS_NOT_EMPTY' },
22
24
  },
23
25
  });
24
26
 
package/src/metadata.js CHANGED
@@ -22,6 +22,26 @@ const unwrap = (type) => {
22
22
  return { named, required, list, itemRequired };
23
23
  };
24
24
 
25
+ // Follows a validated scalar's baseScalarType chain to the scalar it is stored as, stopping where the
26
+ // chain repeats, as MongoDB's resolveStorageScalar does.
27
+ const rootScalar = (type) => {
28
+ let base = type;
29
+ const visited = new Set();
30
+ while (base?.baseScalarType && !visited.has(base)) {
31
+ visited.add(base);
32
+ base = base.baseScalarType;
33
+ }
34
+ return base;
35
+ };
36
+
37
+ /**
38
+ * Internal: the name of the scalar a field type is stored as: the end of its baseScalarType chain, by
39
+ * its own name (`Date` stays `Date`). An enum or a scalar without a base gives its own name, and a
40
+ * chain that repeats stops where it repeats. Never throws; describeModels rejects cyclic chains and
41
+ * unsupported scalars on top of it.
42
+ */
43
+ export const effectiveScalarName = (type) => rootScalar(type)?.name;
44
+
25
45
  const scalarDescription = (type) => {
26
46
  if (isEnumType(type)) {
27
47
  const storedValues = new Map();
@@ -32,14 +52,10 @@ const scalarDescription = (type) => {
32
52
  }
33
53
  return { scalar: 'Enum', values: [...storedValues.keys()], enumValues: type.getValues().map(({ name, value }) => ({ name, value })) };
34
54
  }
35
- let base = type;
36
- const visited = new Set();
37
- while (base.baseScalarType) {
38
- if (visited.has(base)) invalid(`Cyclic base scalar ${type.name}`);
39
- visited.add(base);
40
- base = base.baseScalarType;
41
- }
42
- const scalar = ['DateTime', 'Date', 'Time'].includes(base.name) ? 'DateTime' : base.name;
55
+ // The walk stops on a type that still has a base only where the chain repeats.
56
+ if (rootScalar(type).baseScalarType) invalid(`Cyclic base scalar ${type.name}`);
57
+ const name = effectiveScalarName(type);
58
+ const scalar = ['DateTime', 'Date', 'Time'].includes(name) ? 'DateTime' : name;
43
59
  if (!['String', 'ID', 'Int', 'Float', 'Boolean', 'DateTime'].includes(scalar)) {
44
60
  invalid(`Unsupported scalar ${type.name}: declare a supported baseScalarType`);
45
61
  }
@@ -0,0 +1,297 @@
1
+ import {
2
+ getNamedType, isInterfaceType, isObjectType, isScalarType, isUnionType,
3
+ } from 'graphql';
4
+ import SimfinityError from './errors/simfinity.error.js';
5
+ import { effectiveScalarName } from './metadata.js';
6
+ import { getListShape, isVirtualField, normalizeConnectionField } from './relation-storage.js';
7
+
8
+ // Internal: what the emptiness operators IS_EMPTY and IS_NOT_EMPTY (#108, parts 2a and 2b) mean for a
9
+ // path, shared by the runtime gate, the query plan and the MongoDB compiler through the
10
+ // `./internal/query-operators` subpath, which re-exports it and is not public API. Each backend
11
+ // compiles the shape described here to its own forms.
12
+
13
+ /** The emptiness operators, in QLOperator order. IS_NOT_EMPTY is the two-valued complement of IS_EMPTY. */
14
+ export const EMPTINESS_QUERY_OPERATORS = Object.freeze(['IS_EMPTY', 'IS_NOT_EMPTY']);
15
+
16
+ /** Whether `operator` is IS_EMPTY or IS_NOT_EMPTY. */
17
+ export const isEmptinessOperator = (operator) => EMPTINESS_QUERY_OPERATORS.includes(operator);
18
+
19
+ const fail = (message, code) => { throw new SimfinityError(message, code, 400); };
20
+ const pathName = (path) => (Array.isArray(path) ? path.join('.') : path);
21
+
22
+ /**
23
+ * Validates the value of an emptiness condition: it must be omitted (undefined) or null. Anything
24
+ * else, `""`, `[]`, `{}`, `false` and `0` included, fails with INVALID_FILTER_VALUE (400). `path`
25
+ * names the condition in the message. Returns null, the value the plan carries.
26
+ */
27
+ export const validateEmptinessValue = (operator, value, path) => {
28
+ if (value !== undefined && value !== null) {
29
+ fail(`${operator} takes no value${path == null ? '' : ` on ${pathName(path)}`}: omit it or pass null`, 'INVALID_FILTER_VALUE');
30
+ }
31
+ return null;
32
+ };
33
+
34
+ const PATH_SEGMENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
35
+ // The record identity, an entity's own `id` or `_id`, is never empty in practice: PostgreSQL stores it
36
+ // as a uuid primary key even when it is declared String. It is the queried entity's at the root, and
37
+ // the target's right after a single reference.
38
+ const IDENTITY = ['id', '_id'];
39
+ const LISTS = { embeddedList: 'an embedded list', collection: 'a collection' };
40
+
41
+ // A path step or a member, classified as MongoDB reads paths: interface and union types first, then an
42
+ // object field without a relation or with `embedded: true` is embedded, and any other object field is
43
+ // a collection when it is a list and a reference otherwise. `node` is what members are read from (an
44
+ // object type, or a description's `fields`), and `string` tells a String scalar. A reference or a
45
+ // collection names its `target` type, and a collection the child's storage column that links it,
46
+ // `connectionField`, derived as MongoDB derives it; without a declared connectionField a collection
47
+ // reads through its own field name.
48
+ const graphqlStep = (name, field) => {
49
+ const type = getNamedType(field.type);
50
+ const list = !!getListShape(field.type);
51
+ if (isInterfaceType(type) || isUnionType(type)) return { name, kind: 'abstract' };
52
+ if (isObjectType(type)) {
53
+ const relation = field.extensions?.relation;
54
+ const embedded = !relation || relation.embedded;
55
+ const kind = embedded ? (list ? 'embeddedList' : 'embedded') : (list ? 'collection' : 'reference');
56
+ const step = { name, typeName: type.name, node: type, kind };
57
+ if (kind === 'reference') step.target = type.name;
58
+ if (kind === 'collection') {
59
+ Object.assign(step, { target: type.name, connectionField: normalizeConnectionField(type, relation.connectionField || name).storageFieldName });
60
+ }
61
+ return step;
62
+ }
63
+ return { name, kind: list ? 'scalarList' : 'scalar', string: isScalarType(type) && effectiveScalarName(type) === 'String' };
64
+ };
65
+ // Virtual members store nothing and are never read.
66
+ const graphqlMembers = (type) => Object.entries(type.getFields())
67
+ .filter(([, field]) => !isVirtualField(field)).map(([name, field]) => graphqlStep(name, field));
68
+
69
+ // The same classification of a describeModels field description: inferred inverse references are ID
70
+ // scalars, as GraphQL exposes them. Descriptions hold no interface or union fields, and describeModels
71
+ // has already normalized a collection's connectionField to the child's storage column.
72
+ const modelStep = (field) => {
73
+ if (field.kind === 'embedded') return { name: field.name, kind: field.list ? 'embeddedList' : 'embedded', node: field.fields ?? [] };
74
+ if (field.kind === 'collection') return { name: field.name, kind: 'collection', target: field.target, connectionField: field.connectionField };
75
+ if (field.kind === 'reference' && !field.inferred) return { name: field.name, kind: 'reference', target: field.target };
76
+ return { name: field.name, kind: field.list ? 'scalarList' : 'scalar', string: field.scalar === 'String' };
77
+ };
78
+ const modelMembers = (fields) => fields.filter((field) => !field.private).map(modelStep);
79
+
80
+ const isRelation = (step) => step.kind === 'reference' || step.kind === 'collection';
81
+ const leafShape = (step, identity) => {
82
+ if (step.kind === 'scalarList' || step.kind === 'embeddedList') return { rule: 'list' };
83
+ if (identity && IDENTITY.includes(step.name)) return { rule: 'null' };
84
+ return { rule: step.string ? 'string' : 'null' };
85
+ };
86
+ const relationShape = (step) => (step.kind === 'reference'
87
+ ? { rule: 'reference', target: step.target }
88
+ : { rule: 'collection', target: step.target, connectionField: step.connectionField });
89
+
90
+ // Rules 3 to 6 of the order of checks, on a path whose fields resolved (rule 1): rule 3 throws as
91
+ // soon as it is found; a cycle (rule 4) and a reference or collection (rule 6) are recorded, are not
92
+ // entered, and throw only once the whole path and its members passed rule 3, with the value (rule 5)
93
+ // checked between them. Rule 6 throws only when the caller does not support reference emptiness;
94
+ // otherwise a reference or collection end or member gets its own shape, and each single reference the
95
+ // path crosses is listed in `crossings`.
96
+ const describeSteps = (steps, {
97
+ operator, value, label, membersOf, referenceEmptiness,
98
+ }) => {
99
+ const segments = steps.map((step) => step.name);
100
+ const prefix = (index) => segments.slice(0, index + 1).join('.');
101
+ let cycle = null;
102
+ let unsupported = null;
103
+ const crossings = [];
104
+ const abstract = (path) => fail(`${operator} cannot test ${label}: ${path} is an interface or union field, whose emptiness is not defined`, 'INVALID_FILTER_PATH');
105
+ for (const [index, step] of steps.entries()) {
106
+ const list = index > 0 ? LISTS[steps[index - 1].kind] : null;
107
+ if (list) {
108
+ fail(`${operator} cannot test ${label}: emptiness of a value inside a list is not defined, and ${prefix(index - 1)} is ${list}`, 'INVALID_FILTER_PATH');
109
+ }
110
+ if (step.kind === 'abstract') abstract(prefix(index));
111
+ if (!unsupported && isRelation(step)) {
112
+ unsupported = `${operator} on ${label} ${index === steps.length - 1 ? 'ends at' : 'crosses'} the ${step.kind} ${prefix(index)}`;
113
+ }
114
+ // Only a single reference can be crossed: rule 3 rejects any step after a collection.
115
+ if (step.kind === 'reference' && index < steps.length - 1) crossings.push({ path: prefix(index), target: step.target });
116
+ }
117
+ // The member rule: each stored member by its own rule, single embedded members recursively, lists
118
+ // by the list rule without looking inside their items, references and collections by their own
119
+ // rules without entering them.
120
+ const expand = (node, base, ancestors) => {
121
+ const members = [];
122
+ for (const member of membersOf(node)) {
123
+ const memberPath = [...base, member.name].join('.');
124
+ if (member.kind === 'abstract') abstract(memberPath);
125
+ if (isRelation(member)) {
126
+ unsupported ??= `${operator} on ${label} reads the ${member.kind} member ${memberPath}`;
127
+ members.push({ name: member.name, shape: relationShape(member) });
128
+ } else if (member.kind !== 'embedded') {
129
+ members.push({ name: member.name, shape: leafShape(member, false) });
130
+ } else if (ancestors.includes(member.node)) {
131
+ cycle ??= `${operator} cannot test ${label}: the embedded type ${member.typeName ?? `of ${memberPath}`} reaches itself through the single embedded member ${memberPath}`;
132
+ } else {
133
+ members.push({ name: member.name, shape: { rule: 'object', members: expand(member.node, [...base, member.name], [...ancestors, member.node]) } });
134
+ }
135
+ }
136
+ return members;
137
+ };
138
+ const last = steps.at(-1);
139
+ let shape;
140
+ if (last.kind === 'embedded') shape = { rule: 'object', members: expand(last.node, segments, [last.node]) };
141
+ else if (isRelation(last)) shape = relationShape(last);
142
+ else shape = leafShape(last, steps.length === 1 || steps.at(-2).kind === 'reference');
143
+ if (cycle) fail(cycle, 'INVALID_FILTER_OPERATOR');
144
+ validateEmptinessValue(operator, value, label);
145
+ if (unsupported && !referenceEmptiness) {
146
+ fail(`${unsupported}: the database adapter does not support emptiness through references and collections`, 'UNSUPPORTED_QUERY');
147
+ }
148
+ return crossings.length ? { ...shape, crossings } : shape;
149
+ };
150
+
151
+ // Rule 1 on GraphQL types: segment syntax and declared, stored fields, with resolveModelPath's codes
152
+ // and messages; nothing is traversed after a field that is not an object.
153
+ const graphqlSteps = (gqltype, segments, path) => {
154
+ const parts = typeof segments === 'string' ? segments.split('.') : segments;
155
+ if (!Array.isArray(parts) || !parts.length || parts.some((part) => typeof part !== 'string' || !PATH_SEGMENT.test(part))) {
156
+ fail('Invalid filter path', 'INVALID_FILTER_PATH');
157
+ }
158
+ const label = path == null ? parts.join('.') : pathName(path);
159
+ const steps = [];
160
+ let type = gqltype;
161
+ for (const [index, name] of parts.entries()) {
162
+ const fields = isObjectType(type) ? type.getFields() : null;
163
+ if (!fields || !Object.hasOwn(fields, name)) fail(`Unknown field ${parts.slice(0, index + 1).join('.')}`, 'INVALID_FILTER_FIELD');
164
+ if (isVirtualField(fields[name])) {
165
+ fail(`Query path ${label} uses the virtual field ${type.name}.${name}, which is not stored`, 'INVALID_FILTER_FIELD');
166
+ }
167
+ const step = graphqlStep(name, fields[name]);
168
+ if (index < parts.length - 1 && !step.node) fail(`Field ${name} cannot be traversed`, 'INVALID_FILTER_PATH');
169
+ steps.push(step);
170
+ type = step.node;
171
+ }
172
+ return { steps, label };
173
+ };
174
+
175
+ /**
176
+ * Describes what an emptiness condition tests on a path of `gqltype`, the queried type, and applies
177
+ * the checks of #108 part 2a in their order: rule 1 (segment syntax and declared, stored fields, with
178
+ * resolveModelPath's codes and messages; nothing is traversed after a field that is not an object),
179
+ * then rule 3 (INVALID_FILTER_PATH for a segment after an embedded list or a collection, and for an
180
+ * interface or union field on the path or among the members), rule 4 (INVALID_FILTER_OPERATOR when
181
+ * the members re-enter an embedded type through single embedded members), rule 5 (the value, as
182
+ * validateEmptinessValue checks it) and, with `referenceEmptiness: false`, rule 6 (UNSUPPORTED_QUERY
183
+ * when the path crosses or ends at a reference or a collection, or a member is one, for a caller whose
184
+ * database adapter does not support reference emptiness, #108 part 2b). Form, depth and the adapter's
185
+ * operators are the caller's checks. `segments` is an array or a dotted string; `path` names the
186
+ * condition in messages.
187
+ *
188
+ * Returns the shape: `{ rule: 'string' }` (missing, null or ""), `{ rule: 'null' }` (missing or
189
+ * null; the record identity, at the root or right after a single reference, always, whatever scalar
190
+ * it is declared with), `{ rule: 'list' }` (missing, null or []), `{ rule: 'object', members: [{
191
+ * name, shape }] }` (missing, null, or every stored member empty), `{ rule: 'reference', target }`
192
+ * (no record the reference points to) or `{ rule: 'collection', target, connectionField }` (no child
193
+ * record whose `connectionField`, the child's storage column, points to the record); `target` is the
194
+ * type name. The members of an object take these shapes too. When the path crosses single references,
195
+ * the shape also lists them in path order as `crossings: [{ path, target }]`, with `path` the dotted
196
+ * path of the reference from the queried type; emptinessScopePaths reads them.
197
+ */
198
+ export const describeEmptiness = (gqltype, segments, {
199
+ operator = 'IS_EMPTY', value, path, referenceEmptiness = true,
200
+ } = {}) => {
201
+ const { steps, label } = graphqlSteps(gqltype, segments, path);
202
+ return describeSteps(steps, {
203
+ operator, value, label, membersOf: graphqlMembers, referenceEmptiness,
204
+ });
205
+ };
206
+
207
+ /**
208
+ * Rule 1 of {@link describeEmptiness} alone, with its codes and messages, for a caller that applies a
209
+ * check of its own between rule 1 and rules 3 to 6, as the runtime gate applies the adapter's
210
+ * operators (rule 2). Throws for a path that does not fully resolve on `gqltype`; returns nothing.
211
+ */
212
+ export const assertEmptinessPath = (gqltype, segments, { path } = {}) => {
213
+ graphqlSteps(gqltype, segments, path);
214
+ };
215
+
216
+ /**
217
+ * The same description from model metadata, for a description whose entities carry no GraphQL type:
218
+ * `steps` are the field descriptions resolveModelPath returns for the path, so rule 1 is already
219
+ * done. Gives the shapes, codes and messages of {@link describeEmptiness} for the same types.
220
+ */
221
+ export const describeModelEmptiness = (steps, {
222
+ operator = 'IS_EMPTY', value, path, referenceEmptiness = true,
223
+ } = {}) => {
224
+ if (!Array.isArray(steps) || !steps.length) fail('Invalid filter path', 'INVALID_FILTER_PATH');
225
+ const classified = steps.map(modelStep);
226
+ const label = path == null ? classified.map((step) => step.name).join('.') : pathName(path);
227
+ return describeSteps(classified, {
228
+ operator, value, label, membersOf: modelMembers, referenceEmptiness,
229
+ });
230
+ };
231
+
232
+ // The scoped joins and frames of one emptiness construct, as `[{ path, kind, target }]`: each crossing
233
+ // in path order, then the end and the reference and collection members, depth first in field order.
234
+ const scopeEntries = (shape, path) => {
235
+ const entries = (shape?.crossings ?? []).map(({ path: crossing, target }) => ({ path: crossing, kind: 'join', target }));
236
+ const visit = (node, at) => {
237
+ if (node?.rule === 'reference' || node?.rule === 'collection') entries.push({ path: at, kind: 'frame', target: node.target });
238
+ else if (node?.rule === 'object') for (const member of node.members) visit(member.shape, `${at}.${member.name}`);
239
+ };
240
+ visit(shape, pathName(path));
241
+ return entries;
242
+ };
243
+
244
+ /**
245
+ * The reference and collection paths that one emptiness construct reads, from the shape that
246
+ * describeEmptiness or describeModelEmptiness gave for its `path` (an array or a dotted string):
247
+ * `joins` are the single references the path crosses (one scoped join each, for a client construct),
248
+ * and `frames` the end when it is a reference or a collection, then each reference and collection
249
+ * member (one frame each). Every path is dotted and starts at the queried type. A construct on the
250
+ * record's own fields gives two empty lists.
251
+ */
252
+ export const emptinessScopePaths = (shape, path) => {
253
+ const entries = scopeEntries(shape, path);
254
+ return {
255
+ joins: entries.filter((entry) => entry.kind === 'join').map((entry) => entry.path),
256
+ frames: entries.filter((entry) => entry.kind === 'frame').map((entry) => entry.path),
257
+ };
258
+ };
259
+
260
+ /**
261
+ * The target type name of every path {@link emptinessScopePaths} lists, as `{ [path]: target }`,
262
+ * joins first: the type whose `find` scope restricts that join or frame.
263
+ */
264
+ export const emptinessScopeTargets = (shape, path) => Object.fromEntries(
265
+ scopeEntries(shape, path).map((entry) => [entry.path, entry.target]),
266
+ );
267
+
268
+ /**
269
+ * The stored member paths an emptiness condition reads when its path, on `gqltype`, ends at a single
270
+ * embedded object: absolute segment arrays, depth first in field order, entering single embedded
271
+ * members and nothing else. Virtual members are left out. A list, reference, collection, interface or
272
+ * union member is listed and not entered, and so is a single embedded member whose type is already on
273
+ * the chain being listed. A path that does not resolve to a single embedded object lists nothing. The
274
+ * path is followed as walkQueryPath follows it. Never throws; every code comes from the checks.
275
+ */
276
+ export const emptinessMemberPaths = (gqltype, segments) => {
277
+ const paths = [];
278
+ if (!Array.isArray(segments) || !segments.length) return paths;
279
+ let type = gqltype;
280
+ let last = null;
281
+ for (const name of segments) {
282
+ const fields = typeof type?.getFields === 'function' ? type.getFields() : null;
283
+ if (!fields || typeof name !== 'string' || !Object.hasOwn(fields, name) || isVirtualField(fields[name])) return paths;
284
+ last = graphqlStep(name, fields[name]);
285
+ type = getNamedType(fields[name].type);
286
+ }
287
+ if (last.kind !== 'embedded') return paths;
288
+ const visit = (node, base, ancestors) => {
289
+ for (const member of graphqlMembers(node)) {
290
+ const memberPath = [...base, member.name];
291
+ paths.push(memberPath);
292
+ if (member.kind === 'embedded' && !ancestors.includes(member.node)) visit(member.node, memberPath, [...ancestors, member.node]);
293
+ }
294
+ };
295
+ visit(last.node, segments, [last.node]);
296
+ return paths;
297
+ };
@@ -1,21 +1,33 @@
1
1
  import SimfinityError from './errors/simfinity.error.js';
2
2
 
3
3
  let queryMaxPageSize = 1000;
4
+ let queryMaxReferenceFrames = 10;
4
5
 
6
+ const isPositiveSafeInteger = (value) => Number.isSafeInteger(value) && value >= 1;
7
+
8
+ // Process-wide. Each omitted option takes its default again, and every option is checked before any
9
+ // is assigned, so a call that fails keeps every current limit. `maxReferenceFrames` caps, per resolver
10
+ // call, the distinct scoped joins and frames of a client's reference emptiness (#108 part 2b).
5
11
  export const configureQueryLimits = (options = {}) => {
6
12
  if (!options || typeof options !== 'object' || Array.isArray(options)
7
13
  || ![Object.prototype, null].includes(Object.getPrototypeOf(options))) {
8
14
  throw new SimfinityError('Query limit options must be a plain object', 'INVALID_QUERY_LIMITS', 400);
9
15
  }
10
- const { maxPageSize = 1000 } = options;
11
- if (!Number.isSafeInteger(maxPageSize) || maxPageSize < 1) {
16
+ const { maxPageSize = 1000, maxReferenceFrames = 10 } = options;
17
+ if (!isPositiveSafeInteger(maxPageSize)) {
12
18
  throw new SimfinityError('maxPageSize must be a positive safe integer', 'INVALID_QUERY_LIMITS', 400);
13
19
  }
20
+ if (!isPositiveSafeInteger(maxReferenceFrames)) {
21
+ throw new SimfinityError('maxReferenceFrames must be a positive safe integer', 'INVALID_QUERY_LIMITS', 400);
22
+ }
14
23
  queryMaxPageSize = maxPageSize;
24
+ queryMaxReferenceFrames = maxReferenceFrames;
15
25
  };
16
26
 
17
27
  export const getQueryMaxPageSize = () => queryMaxPageSize;
18
28
 
29
+ export const getQueryMaxReferenceFrames = () => queryMaxReferenceFrames;
30
+
19
31
  export const paginationStages = (pagination, withDefault) => {
20
32
  if (pagination == null) return withDefault ? [{ $skip: 0 }, { $limit: Math.min(100, queryMaxPageSize) }] : [];
21
33
  const { page, size } = pagination;
@@ -3,7 +3,14 @@ import SimfinityError from './errors/simfinity.error.js';
3
3
 
4
4
  // Internal: the filter operators and the value rules every backend applies to them. They are shared
5
5
  // by the core runtime, the query plan and the MongoDB compiler through the
6
- // `./internal/query-operators` subpath, which is not public API.
6
+ // `./internal/query-operators` subpath, which is not public API. The emptiness operators live in
7
+ // query-emptiness.js and are re-exported here, so the subpath stays the only one.
8
+
9
+ export {
10
+ EMPTINESS_QUERY_OPERATORS, describeEmptiness, describeModelEmptiness, emptinessMemberPaths, emptinessScopePaths,
11
+ emptinessScopeTargets, isEmptinessOperator, validateEmptinessValue,
12
+ } from './query-emptiness.js';
13
+ export { effectiveScalarName } from './metadata.js';
7
14
 
8
15
  /** Every `QLOperator` value, in declaration order. QLOperator is the only list of operators. */
9
16
  export const QUERY_OPERATORS = Object.freeze(QLOperator.getValues().map((entry) => entry.value));
@@ -61,20 +68,25 @@ const invalidFeatures = (message) => {
61
68
  };
62
69
 
63
70
  /**
64
- * Reads an adapter's `queryFeatures` declaration into the set of operators it compiles. Without a
65
- * declaration (undefined or null) the adapter supports {@link LEGACY_QUERY_OPERATORS}. A declaration
66
- * is an object whose `operators` is an array of operator names; names this version does not
67
- * know are ignored, and other members are left for later features. Anything else throws
68
- * `INVALID_QUERY_FEATURES` (500).
71
+ * Reads an adapter's `queryFeatures` declaration into `{ operators, referenceEmptiness }`: the set of
72
+ * operators it compiles, and whether it compiles emptiness through references and collections (#108
73
+ * part 2b). Without a declaration (undefined or null) the adapter supports {@link
74
+ * LEGACY_QUERY_OPERATORS} and no reference emptiness. A declaration is an object whose `operators`
75
+ * is an array of operator names, whose names this version does not know are ignored, and whose
76
+ * optional `referenceEmptiness` is a boolean, undefined or null (false); other members are left for
77
+ * later features. Anything else throws `INVALID_QUERY_FEATURES` (500).
69
78
  */
70
79
  export const resolveQueryFeatures = (queryFeatures) => {
71
- if (queryFeatures == null) return { operators: new Set(LEGACY_QUERY_OPERATORS) };
80
+ if (queryFeatures == null) return { operators: new Set(LEGACY_QUERY_OPERATORS), referenceEmptiness: false };
72
81
  if (typeof queryFeatures !== 'object' || Array.isArray(queryFeatures)) {
73
82
  invalidFeatures('must be an object with an operators array');
74
83
  }
75
- const { operators } = queryFeatures;
84
+ const { operators, referenceEmptiness } = queryFeatures;
76
85
  if (!Array.isArray(operators) || operators.some((operator) => typeof operator !== 'string')) {
77
86
  invalidFeatures('operators must be an array of operator names');
78
87
  }
79
- return { operators: new Set(operators.filter(isQueryOperator)) };
88
+ if (referenceEmptiness != null && typeof referenceEmptiness !== 'boolean') {
89
+ invalidFeatures('referenceEmptiness must be a boolean');
90
+ }
91
+ return { operators: new Set(operators.filter(isQueryOperator)), referenceEmptiness: referenceEmptiness === true };
80
92
  };