graphile-sql-expression-validator 2.11.1 → 2.12.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/field-types.js ADDED
@@ -0,0 +1,631 @@
1
+ "use strict";
2
+ /**
3
+ * FieldType and FieldDefault: structured JSONB models for PostgreSQL
4
+ * type declarations and default value expressions.
5
+ *
6
+ * These models provide a safe, validated representation that can be:
7
+ * 1. Validated structurally (JSON shape, identifier patterns, allowlists)
8
+ * 2. Converted to pgsql-parser AST nodes
9
+ * 3. Validated at the AST level (reuses the expression validator for defaults)
10
+ * 4. Deparsed to canonical SQL text
11
+ *
12
+ * The key security insight: the structured model eliminates entire attack
13
+ * categories by construction (no subqueries, no column refs, no stacked
14
+ * statements). What remains is identifier validation + allowlist enforcement.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.FORBIDDEN_TYPES = void 0;
18
+ exports.fieldTypeToAst = fieldTypeToAst;
19
+ exports.fieldTypeToSql = fieldTypeToSql;
20
+ exports.fieldDefaultToAst = fieldDefaultToAst;
21
+ exports.fieldDefaultToSql = fieldDefaultToSql;
22
+ exports.validateFieldType = validateFieldType;
23
+ exports.validateFieldDefault = validateFieldDefault;
24
+ const pgsql_deparser_1 = require("pgsql-deparser");
25
+ const validator_1 = require("./validator");
26
+ // ─── Constants ───────────────────────────────────────────────────
27
+ /** Valid SQL identifier pattern. */
28
+ const IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
29
+ /**
30
+ * PostgreSQL system catalog type casts that are forbidden.
31
+ * These OID-alias types can be used to probe the system catalog.
32
+ * Shared with the expression validator (same list).
33
+ */
34
+ exports.FORBIDDEN_TYPES = new Set([
35
+ 'regclass',
36
+ 'regtype',
37
+ 'regproc',
38
+ 'regprocedure',
39
+ 'regoper',
40
+ 'regoperator',
41
+ 'regnamespace',
42
+ 'regrole',
43
+ 'regconfig',
44
+ 'regdictionary'
45
+ ]);
46
+ /**
47
+ * Valid interval field qualifiers for the `range` property.
48
+ */
49
+ const VALID_INTERVAL_FIELDS = new Set([
50
+ 'year', 'month', 'day', 'hour', 'minute', 'second'
51
+ ]);
52
+ /** Allowed keys in a FieldType object. */
53
+ const FIELD_TYPE_KEYS = new Set(['name', 'schema', 'args', 'array_dimensions', 'range']);
54
+ /** Allowed keys in a FieldDefault object. */
55
+ const FIELD_DEFAULT_KEYS = new Set(['value', 'function', 'schema', 'args', 'cast']);
56
+ // ─── Internal: AST Builders ──────────────────────────────────────
57
+ /** Build a pgsql-parser String node. */
58
+ function astString(sval) {
59
+ return { String: { sval } };
60
+ }
61
+ /** Build a pgsql-parser A_Const node for an integer. */
62
+ function astConstInt(ival) {
63
+ return { A_Const: { ival: { ival } } };
64
+ }
65
+ /** Build a pgsql-parser A_Const node for a string. */
66
+ function astConstStr(sval) {
67
+ return { A_Const: { sval: { sval } } };
68
+ }
69
+ /** Build a pgsql-parser A_Const node for a boolean. */
70
+ function astConstBool(boolval) {
71
+ if (boolval) {
72
+ return { A_Const: { boolval: { boolval: true } } };
73
+ }
74
+ return { A_Const: { boolval: {} } };
75
+ }
76
+ /** Build a pgsql-parser A_Const node for NULL. */
77
+ function astConstNull() {
78
+ return { A_Const: { isnull: true } };
79
+ }
80
+ // ─── Converters: FieldType → AST ─────────────────────────────────
81
+ /**
82
+ * Convert a FieldType to a pgsql-parser TypeName AST node.
83
+ *
84
+ * The TypeName node format:
85
+ * {
86
+ * names: [{ String: { sval: "schema" } }, { String: { sval: "name" } }],
87
+ * typmods: [<arg AST nodes>],
88
+ * arrayBounds: [{ Integer: { ival: -1 } }, ...],
89
+ * typemod: -1
90
+ * }
91
+ */
92
+ function fieldTypeToAst(ft) {
93
+ const names = [];
94
+ if (ft.schema) {
95
+ names.push(astString(ft.schema));
96
+ }
97
+ names.push(astString(ft.name));
98
+ const typeName = {
99
+ names,
100
+ typemod: -1
101
+ };
102
+ // Type arguments → typmods
103
+ if (ft.args && ft.args.length > 0) {
104
+ const typmods = [];
105
+ for (const arg of ft.args) {
106
+ if (typeof arg === 'number') {
107
+ typmods.push(astConstInt(arg));
108
+ }
109
+ else if (typeof arg === 'string') {
110
+ // String args in type modifiers are identifiers (e.g., "Point" in geometry(Point, 4326))
111
+ // PostgreSQL parser represents these as ColumnRef nodes
112
+ typmods.push({
113
+ ColumnRef: {
114
+ fields: [astString(arg.toLowerCase())]
115
+ }
116
+ });
117
+ }
118
+ else if (typeof arg === 'boolean') {
119
+ typmods.push(astConstBool(arg));
120
+ }
121
+ }
122
+ typeName.typmods = typmods;
123
+ }
124
+ // Array dimensions → arrayBounds
125
+ if (ft.array_dimensions && ft.array_dimensions > 0) {
126
+ const arrayBounds = [];
127
+ for (let i = 0; i < ft.array_dimensions; i++) {
128
+ arrayBounds.push({ Integer: { ival: -1 } });
129
+ }
130
+ typeName.arrayBounds = arrayBounds;
131
+ }
132
+ // Interval range is encoded as a numeric typmod by PostgreSQL.
133
+ // We store it as readable strings; conversion to the numeric bitmask
134
+ // happens in field_type_to_text() at the SQL layer.
135
+ // For AST purposes, we skip typmods for interval range — the deparser
136
+ // handles it via the INTERVAL keyword + field qualifiers.
137
+ return typeName;
138
+ }
139
+ /**
140
+ * Convert a FieldType to its canonical SQL text representation.
141
+ *
142
+ * Uses the deparser for the base type, then appends array brackets.
143
+ * Handles interval range fields manually since the deparser needs
144
+ * special handling for INTERVAL ... DAY TO SECOND syntax.
145
+ */
146
+ function fieldTypeToSql(ft) {
147
+ // Build the base type string
148
+ let sql = '';
149
+ if (ft.schema) {
150
+ sql += ft.schema + '.';
151
+ }
152
+ sql += ft.name;
153
+ // Type arguments
154
+ if (ft.args && ft.args.length > 0) {
155
+ const argParts = ft.args.map(arg => {
156
+ if (typeof arg === 'string')
157
+ return arg;
158
+ return String(arg);
159
+ });
160
+ sql += '(' + argParts.join(', ') + ')';
161
+ }
162
+ // Interval range
163
+ if (ft.range && ft.range.length > 0 && ft.name.toLowerCase() === 'interval') {
164
+ if (ft.range.length === 1) {
165
+ sql += ' ' + ft.range[0];
166
+ }
167
+ else if (ft.range.length === 2) {
168
+ sql += ' ' + ft.range[0] + ' to ' + ft.range[1];
169
+ }
170
+ }
171
+ // Array dimensions
172
+ if (ft.array_dimensions && ft.array_dimensions > 0) {
173
+ for (let i = 0; i < ft.array_dimensions; i++) {
174
+ sql += '[]';
175
+ }
176
+ }
177
+ return sql;
178
+ }
179
+ // ─── Converters: FieldDefault → AST ─────────────────────────────
180
+ /**
181
+ * Convert a FieldDefault to a pgsql-parser expression AST node.
182
+ *
183
+ * Handles:
184
+ * - Literal values → A_Const
185
+ * - Function calls → FuncCall (with recursive args)
186
+ * - Type casts → TypeCast wrapping the inner expression
187
+ * - Combinations (function + cast, value + cast)
188
+ */
189
+ function fieldDefaultToAst(fd, depth = 0) {
190
+ if (depth > 10) {
191
+ throw new Error('FieldDefault nesting exceeds maximum depth');
192
+ }
193
+ let expr;
194
+ if (fd.function !== undefined) {
195
+ // Function call
196
+ const funcname = [];
197
+ if (fd.schema) {
198
+ funcname.push(astString(fd.schema));
199
+ }
200
+ funcname.push(astString(fd.function));
201
+ const funcCall = {
202
+ funcname,
203
+ funcformat: 'COERCE_EXPLICIT_CALL'
204
+ };
205
+ // Function arguments
206
+ if (fd.args && fd.args.length > 0) {
207
+ const astArgs = [];
208
+ for (const arg of fd.args) {
209
+ astArgs.push(fieldDefaultArgToAst(arg, depth + 1));
210
+ }
211
+ funcCall.args = astArgs;
212
+ }
213
+ expr = { FuncCall: funcCall };
214
+ }
215
+ else if (fd.value !== undefined) {
216
+ // Literal value
217
+ expr = literalToAst(fd.value);
218
+ }
219
+ else {
220
+ throw new Error('FieldDefault must have either "function" or "value"');
221
+ }
222
+ // Wrap in TypeCast if cast is present
223
+ if (fd.cast) {
224
+ expr = {
225
+ TypeCast: {
226
+ arg: expr,
227
+ typeName: fieldTypeToAst(fd.cast)
228
+ }
229
+ };
230
+ }
231
+ return expr;
232
+ }
233
+ /**
234
+ * Convert a FieldDefaultArg to an AST node.
235
+ */
236
+ function fieldDefaultArgToAst(arg, depth) {
237
+ if (arg === null) {
238
+ return astConstNull();
239
+ }
240
+ if (typeof arg === 'string') {
241
+ return astConstStr(arg);
242
+ }
243
+ if (typeof arg === 'number') {
244
+ if (Number.isInteger(arg)) {
245
+ return astConstInt(arg);
246
+ }
247
+ // Float — represented as string in pgsql-parser
248
+ return { A_Const: { fval: { fval: String(arg) } } };
249
+ }
250
+ if (typeof arg === 'boolean') {
251
+ return astConstBool(arg);
252
+ }
253
+ // Nested FieldDefault object
254
+ return fieldDefaultToAst(arg, depth);
255
+ }
256
+ /**
257
+ * Convert a literal value to an A_Const (or A_ArrayExpr) AST node.
258
+ */
259
+ function literalToAst(value) {
260
+ if (value === null) {
261
+ return astConstNull();
262
+ }
263
+ if (typeof value === 'string') {
264
+ return astConstStr(value);
265
+ }
266
+ if (typeof value === 'number') {
267
+ if (Number.isInteger(value)) {
268
+ return astConstInt(value);
269
+ }
270
+ return { A_Const: { fval: { fval: String(value) } } };
271
+ }
272
+ if (typeof value === 'boolean') {
273
+ return astConstBool(value);
274
+ }
275
+ if (Array.isArray(value)) {
276
+ const elements = value.map(el => {
277
+ if (el === null)
278
+ return astConstNull();
279
+ if (typeof el === 'string')
280
+ return astConstStr(el);
281
+ if (typeof el === 'number') {
282
+ if (Number.isInteger(el))
283
+ return astConstInt(el);
284
+ return { A_Const: { fval: { fval: String(el) } } };
285
+ }
286
+ if (typeof el === 'boolean')
287
+ return astConstBool(el);
288
+ throw new Error(`Unsupported array element type: ${typeof el}`);
289
+ });
290
+ return { A_ArrayExpr: { elements } };
291
+ }
292
+ throw new Error(`Unsupported literal type: ${typeof value}`);
293
+ }
294
+ /**
295
+ * Convert a FieldDefault to its canonical SQL text representation.
296
+ */
297
+ function fieldDefaultToSql(fd) {
298
+ const ast = fieldDefaultToAst(fd);
299
+ return (0, pgsql_deparser_1.deparseSync)([ast]);
300
+ }
301
+ // ─── Structural Validators ───────────────────────────────────────
302
+ /**
303
+ * Validate a FieldType object structurally.
304
+ *
305
+ * Checks:
306
+ * - Object shape (no unknown keys, required keys present)
307
+ * - `name` is a valid SQL identifier
308
+ * - `name` is not a forbidden type (regclass, regtype, etc.)
309
+ * - `schema` (if present) is a valid SQL identifier and on the allowlist
310
+ * - `args` elements are literals (string, number, boolean)
311
+ * - `array_dimensions` is a positive integer
312
+ * - `range` elements are valid interval field qualifiers
313
+ *
314
+ * Then converts to SQL text for canonical output.
315
+ */
316
+ function validateFieldType(ft, options = {}) {
317
+ const { allowedTypeSchemas = [], additionalForbiddenTypes = [] } = options;
318
+ // Must be a non-null object
319
+ if (!ft || typeof ft !== 'object' || Array.isArray(ft)) {
320
+ return { valid: false, error: 'FieldType must be a non-null object' };
321
+ }
322
+ const obj = ft;
323
+ // No unknown keys
324
+ for (const key of Object.keys(obj)) {
325
+ if (!FIELD_TYPE_KEYS.has(key)) {
326
+ return { valid: false, error: `Unknown FieldType key: "${key}"` };
327
+ }
328
+ }
329
+ // name: required, valid identifier
330
+ if (typeof obj.name !== 'string') {
331
+ return { valid: false, error: 'FieldType.name is required and must be a string' };
332
+ }
333
+ if (!IDENTIFIER_PATTERN.test(obj.name)) {
334
+ return {
335
+ valid: false,
336
+ error: `FieldType.name must be a valid SQL identifier, got: "${obj.name}"`
337
+ };
338
+ }
339
+ // Forbidden types
340
+ const nameLower = obj.name.toLowerCase();
341
+ if (exports.FORBIDDEN_TYPES.has(nameLower)) {
342
+ return {
343
+ valid: false,
344
+ error: `Forbidden type: "${obj.name}" — system catalog OID-alias types are not allowed`
345
+ };
346
+ }
347
+ for (const forbidden of additionalForbiddenTypes) {
348
+ if (nameLower === forbidden.toLowerCase()) {
349
+ return {
350
+ valid: false,
351
+ error: `Forbidden type: "${obj.name}"`
352
+ };
353
+ }
354
+ }
355
+ // schema: optional, valid identifier + allowlist
356
+ if (obj.schema !== undefined) {
357
+ if (typeof obj.schema !== 'string') {
358
+ return { valid: false, error: 'FieldType.schema must be a string' };
359
+ }
360
+ if (!IDENTIFIER_PATTERN.test(obj.schema)) {
361
+ return {
362
+ valid: false,
363
+ error: `FieldType.schema must be a valid SQL identifier, got: "${obj.schema}"`
364
+ };
365
+ }
366
+ if (allowedTypeSchemas.length > 0) {
367
+ const schemaLower = obj.schema.toLowerCase();
368
+ if (!allowedTypeSchemas.some(s => s.toLowerCase() === schemaLower)) {
369
+ return {
370
+ valid: false,
371
+ error: `Type schema "${obj.schema}" is not in the allowed schemas list`
372
+ };
373
+ }
374
+ }
375
+ }
376
+ // args: optional, must be array of literals
377
+ if (obj.args !== undefined) {
378
+ if (!Array.isArray(obj.args)) {
379
+ return { valid: false, error: 'FieldType.args must be an array' };
380
+ }
381
+ for (let i = 0; i < obj.args.length; i++) {
382
+ const arg = obj.args[i];
383
+ if (typeof arg !== 'string' && typeof arg !== 'number' && typeof arg !== 'boolean') {
384
+ return {
385
+ valid: false,
386
+ error: `FieldType.args[${i}] must be a string, number, or boolean, got: ${typeof arg}`
387
+ };
388
+ }
389
+ // String args must be valid identifiers (they become type modifiers)
390
+ if (typeof arg === 'string' && !IDENTIFIER_PATTERN.test(arg)) {
391
+ return {
392
+ valid: false,
393
+ error: `FieldType.args[${i}] string must be a valid identifier, got: "${arg}"`
394
+ };
395
+ }
396
+ }
397
+ }
398
+ // array_dimensions: optional, positive integer
399
+ if (obj.array_dimensions !== undefined) {
400
+ if (typeof obj.array_dimensions !== 'number' || !Number.isInteger(obj.array_dimensions)) {
401
+ return { valid: false, error: 'FieldType.array_dimensions must be an integer' };
402
+ }
403
+ if (obj.array_dimensions < 0 || obj.array_dimensions > 6) {
404
+ return {
405
+ valid: false,
406
+ error: 'FieldType.array_dimensions must be between 0 and 6'
407
+ };
408
+ }
409
+ }
410
+ // range: optional, 1-2 valid interval field qualifiers
411
+ if (obj.range !== undefined) {
412
+ if (!Array.isArray(obj.range)) {
413
+ return { valid: false, error: 'FieldType.range must be an array' };
414
+ }
415
+ if (obj.range.length < 1 || obj.range.length > 2) {
416
+ return { valid: false, error: 'FieldType.range must have 1 or 2 elements' };
417
+ }
418
+ for (let i = 0; i < obj.range.length; i++) {
419
+ const field = obj.range[i];
420
+ if (typeof field !== 'string') {
421
+ return {
422
+ valid: false,
423
+ error: `FieldType.range[${i}] must be a string`
424
+ };
425
+ }
426
+ if (!VALID_INTERVAL_FIELDS.has(field.toLowerCase())) {
427
+ return {
428
+ valid: false,
429
+ error: `FieldType.range[${i}] must be a valid interval field (year, month, day, hour, minute, second), got: "${field}"`
430
+ };
431
+ }
432
+ }
433
+ // range only makes sense on interval
434
+ if (nameLower !== 'interval') {
435
+ return {
436
+ valid: false,
437
+ error: 'FieldType.range is only valid for interval types'
438
+ };
439
+ }
440
+ }
441
+ // Generate canonical SQL and AST
442
+ const typedFt = obj;
443
+ try {
444
+ const ast = fieldTypeToAst(typedFt);
445
+ const canonicalSql = fieldTypeToSql(typedFt);
446
+ return { valid: true, canonicalSql, ast };
447
+ }
448
+ catch (e) {
449
+ const msg = e instanceof Error ? e.message : String(e);
450
+ return { valid: false, error: `Failed to convert FieldType to SQL: ${msg}` };
451
+ }
452
+ }
453
+ /**
454
+ * Validate a FieldDefault object.
455
+ *
456
+ * Structural validation + AST conversion + expression validation.
457
+ *
458
+ * 1. Validates the JSON structure (shape, types, required fields)
459
+ * 2. Converts to pgsql-parser expression AST
460
+ * 3. Validates the AST through the expression validator (function/schema allowlists)
461
+ * 4. Deparses to canonical SQL text
462
+ */
463
+ function validateFieldDefault(fd, options = {}) {
464
+ const { maxNestingDepth = 4, allowedTypeSchemas = [], additionalForbiddenTypes = [], allowedSchemaFunctions = {}, ...expressionOptions } = options;
465
+ // Structural validation first
466
+ const structResult = validateFieldDefaultStructure(fd, 0, maxNestingDepth, allowedTypeSchemas, additionalForbiddenTypes);
467
+ if (!structResult.valid) {
468
+ return structResult;
469
+ }
470
+ // Build merged options for the expression validator
471
+ // Include schema-qualified functions in both allowedFunctions and allowedSchemas
472
+ const mergedFunctions = [...(expressionOptions.allowedFunctions ?? [])];
473
+ const mergedSchemas = [...(expressionOptions.allowedSchemas ?? [])];
474
+ for (const [schema, funcs] of Object.entries(allowedSchemaFunctions)) {
475
+ if (!mergedSchemas.some(s => s.toLowerCase() === schema.toLowerCase())) {
476
+ mergedSchemas.push(schema);
477
+ }
478
+ for (const func of funcs) {
479
+ if (!mergedFunctions.some(f => f.toLowerCase() === func.toLowerCase())) {
480
+ mergedFunctions.push(func);
481
+ }
482
+ }
483
+ }
484
+ const mergedExpressionOptions = {
485
+ ...expressionOptions,
486
+ allowedFunctions: mergedFunctions.length > 0 ? mergedFunctions : undefined,
487
+ allowedSchemas: mergedSchemas.length > 0 ? mergedSchemas : undefined
488
+ };
489
+ // Convert to AST
490
+ const typedFd = fd;
491
+ let ast;
492
+ try {
493
+ ast = fieldDefaultToAst(typedFd);
494
+ }
495
+ catch (e) {
496
+ const msg = e instanceof Error ? e.message : String(e);
497
+ return { valid: false, error: `Failed to convert FieldDefault to AST: ${msg}` };
498
+ }
499
+ // Validate the AST through the expression validator
500
+ const astResult = (0, validator_1.validateAst)(ast, mergedExpressionOptions);
501
+ if (!astResult.valid) {
502
+ return { valid: false, error: astResult.error };
503
+ }
504
+ return {
505
+ valid: true,
506
+ canonicalSql: astResult.canonicalText,
507
+ ast
508
+ };
509
+ }
510
+ /**
511
+ * Recursively validate the structure of a FieldDefault object.
512
+ */
513
+ function validateFieldDefaultStructure(fd, depth, maxDepth, allowedTypeSchemas, additionalForbiddenTypes) {
514
+ if (depth > maxDepth) {
515
+ return {
516
+ valid: false,
517
+ error: `FieldDefault nesting exceeds maximum depth of ${maxDepth}`
518
+ };
519
+ }
520
+ if (!fd || typeof fd !== 'object' || Array.isArray(fd)) {
521
+ return { valid: false, error: 'FieldDefault must be a non-null object' };
522
+ }
523
+ const obj = fd;
524
+ // No unknown keys
525
+ for (const key of Object.keys(obj)) {
526
+ if (!FIELD_DEFAULT_KEYS.has(key)) {
527
+ return { valid: false, error: `Unknown FieldDefault key: "${key}"` };
528
+ }
529
+ }
530
+ // Must have either function or value (not both, not neither)
531
+ const hasFunction = obj.function !== undefined;
532
+ const hasValue = obj.value !== undefined;
533
+ if (!hasFunction && !hasValue) {
534
+ return { valid: false, error: 'FieldDefault must have either "function" or "value"' };
535
+ }
536
+ if (hasFunction && hasValue) {
537
+ return { valid: false, error: 'FieldDefault cannot have both "function" and "value"' };
538
+ }
539
+ // schema without function is invalid
540
+ if (obj.schema !== undefined && !hasFunction) {
541
+ return { valid: false, error: 'FieldDefault.schema is only valid with "function"' };
542
+ }
543
+ // args without function is invalid
544
+ if (obj.args !== undefined && !hasFunction) {
545
+ return { valid: false, error: 'FieldDefault.args is only valid with "function"' };
546
+ }
547
+ if (hasFunction) {
548
+ // function: must be valid identifier
549
+ if (typeof obj.function !== 'string') {
550
+ return { valid: false, error: 'FieldDefault.function must be a string' };
551
+ }
552
+ if (!IDENTIFIER_PATTERN.test(obj.function)) {
553
+ return {
554
+ valid: false,
555
+ error: `FieldDefault.function must be a valid SQL identifier, got: "${obj.function}"`
556
+ };
557
+ }
558
+ // schema: optional, valid identifier
559
+ if (obj.schema !== undefined) {
560
+ if (typeof obj.schema !== 'string') {
561
+ return { valid: false, error: 'FieldDefault.schema must be a string' };
562
+ }
563
+ if (!IDENTIFIER_PATTERN.test(obj.schema)) {
564
+ return {
565
+ valid: false,
566
+ error: `FieldDefault.schema must be a valid SQL identifier, got: "${obj.schema}"`
567
+ };
568
+ }
569
+ }
570
+ // args: optional, recursive
571
+ if (obj.args !== undefined) {
572
+ if (!Array.isArray(obj.args)) {
573
+ return { valid: false, error: 'FieldDefault.args must be an array' };
574
+ }
575
+ for (let i = 0; i < obj.args.length; i++) {
576
+ const arg = obj.args[i];
577
+ if (arg === null || typeof arg === 'string' || typeof arg === 'number' || typeof arg === 'boolean') {
578
+ continue; // Literal — valid
579
+ }
580
+ if (typeof arg === 'object') {
581
+ // Nested FieldDefault
582
+ const nestedResult = validateFieldDefaultStructure(arg, depth + 1, maxDepth, allowedTypeSchemas, additionalForbiddenTypes);
583
+ if (!nestedResult.valid) {
584
+ return {
585
+ valid: false,
586
+ error: `FieldDefault.args[${i}]: ${nestedResult.error}`
587
+ };
588
+ }
589
+ }
590
+ else {
591
+ return {
592
+ valid: false,
593
+ error: `FieldDefault.args[${i}] must be a string, number, boolean, null, or FieldDefault object`
594
+ };
595
+ }
596
+ }
597
+ }
598
+ }
599
+ if (hasValue) {
600
+ // value: must be string, number, boolean, null, or array
601
+ const v = obj.value;
602
+ if (v !== null && typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean' && !Array.isArray(v)) {
603
+ return {
604
+ valid: false,
605
+ error: `FieldDefault.value must be a string, number, boolean, null, or array`
606
+ };
607
+ }
608
+ if (Array.isArray(v)) {
609
+ for (let i = 0; i < v.length; i++) {
610
+ const el = v[i];
611
+ if (el !== null && typeof el !== 'string' && typeof el !== 'number' && typeof el !== 'boolean') {
612
+ return {
613
+ valid: false,
614
+ error: `FieldDefault.value[${i}] array elements must be string, number, boolean, or null`
615
+ };
616
+ }
617
+ }
618
+ }
619
+ }
620
+ // cast: optional, must be valid FieldType
621
+ if (obj.cast !== undefined) {
622
+ const castResult = validateFieldType(obj.cast, {
623
+ allowedTypeSchemas,
624
+ additionalForbiddenTypes
625
+ });
626
+ if (!castResult.valid) {
627
+ return { valid: false, error: `FieldDefault.cast: ${castResult.error}` };
628
+ }
629
+ }
630
+ return { valid: true };
631
+ }
package/index.d.ts CHANGED
@@ -33,3 +33,5 @@
33
33
  export { parseAndValidateSqlExpression, validateAst, DEFAULT_ALLOWED_FUNCTIONS } from './validator';
34
34
  export type { SqlExpressionValidatorOptions, SqlExpressionValidationResult, AstValidationResult } from './validator';
35
35
  export { createSqlExpressionValidatorPlugin, SqlExpressionValidatorPreset } from './plugin';
36
+ export { validateFieldType, validateFieldDefault, fieldTypeToAst, fieldTypeToSql, fieldDefaultToAst, fieldDefaultToSql, FORBIDDEN_TYPES } from './field-types';
37
+ export type { FieldType, FieldDefault, FieldDefaultArg, FieldTypeValidationOptions, FieldDefaultValidationOptions, FieldTypeValidationResult, FieldDefaultValidationResult } from './field-types';
package/index.js CHANGED
@@ -32,7 +32,7 @@
32
32
  * ```
33
33
  */
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.SqlExpressionValidatorPreset = exports.createSqlExpressionValidatorPlugin = exports.DEFAULT_ALLOWED_FUNCTIONS = exports.validateAst = exports.parseAndValidateSqlExpression = void 0;
35
+ exports.FORBIDDEN_TYPES = exports.fieldDefaultToSql = exports.fieldDefaultToAst = exports.fieldTypeToSql = exports.fieldTypeToAst = exports.validateFieldDefault = exports.validateFieldType = exports.SqlExpressionValidatorPreset = exports.createSqlExpressionValidatorPlugin = exports.DEFAULT_ALLOWED_FUNCTIONS = exports.validateAst = exports.parseAndValidateSqlExpression = void 0;
36
36
  // Standalone validation utilities
37
37
  var validator_1 = require("./validator");
38
38
  Object.defineProperty(exports, "parseAndValidateSqlExpression", { enumerable: true, get: function () { return validator_1.parseAndValidateSqlExpression; } });
@@ -42,3 +42,12 @@ Object.defineProperty(exports, "DEFAULT_ALLOWED_FUNCTIONS", { enumerable: true,
42
42
  var plugin_1 = require("./plugin");
43
43
  Object.defineProperty(exports, "createSqlExpressionValidatorPlugin", { enumerable: true, get: function () { return plugin_1.createSqlExpressionValidatorPlugin; } });
44
44
  Object.defineProperty(exports, "SqlExpressionValidatorPreset", { enumerable: true, get: function () { return plugin_1.SqlExpressionValidatorPreset; } });
45
+ // FieldType / FieldDefault structured models
46
+ var field_types_1 = require("./field-types");
47
+ Object.defineProperty(exports, "validateFieldType", { enumerable: true, get: function () { return field_types_1.validateFieldType; } });
48
+ Object.defineProperty(exports, "validateFieldDefault", { enumerable: true, get: function () { return field_types_1.validateFieldDefault; } });
49
+ Object.defineProperty(exports, "fieldTypeToAst", { enumerable: true, get: function () { return field_types_1.fieldTypeToAst; } });
50
+ Object.defineProperty(exports, "fieldTypeToSql", { enumerable: true, get: function () { return field_types_1.fieldTypeToSql; } });
51
+ Object.defineProperty(exports, "fieldDefaultToAst", { enumerable: true, get: function () { return field_types_1.fieldDefaultToAst; } });
52
+ Object.defineProperty(exports, "fieldDefaultToSql", { enumerable: true, get: function () { return field_types_1.fieldDefaultToSql; } });
53
+ Object.defineProperty(exports, "FORBIDDEN_TYPES", { enumerable: true, get: function () { return field_types_1.FORBIDDEN_TYPES; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "graphile-sql-expression-validator",
3
- "version": "2.11.1",
3
+ "version": "2.12.0",
4
4
  "description": "SQL expression validation for PostGraphile v5",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "homepage": "https://github.com/constructive-io/constructive",
@@ -56,5 +56,5 @@
56
56
  "@types/node": "^22.19.11",
57
57
  "makage": "^0.3.0"
58
58
  },
59
- "gitHead": "d43f1d7e38cc39a71b4f8d2cafb39f46df12e31a"
59
+ "gitHead": "42ff6bf5fa2e400bb63f78745a1f5a76209677b6"
60
60
  }
package/validator.js CHANGED
@@ -84,7 +84,8 @@ const ALLOWED_NODE_TYPES = new Set([
84
84
  'sval',
85
85
  'fval',
86
86
  'boolval',
87
- 'bsval'
87
+ 'bsval',
88
+ 'isnull'
88
89
  ]);
89
90
  /**
90
91
  * Safe SQLValueFunction.op values.