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