@stonecrop/graphql-middleware 0.8.8 → 0.8.9

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,148 @@
1
+ const handlerRegistry = new Map();
2
+ /**
3
+ * Register an action handler
4
+ * @param name - Unique name for the action handler
5
+ * @param handler - Action handler function to register
6
+ * @public
7
+ */
8
+ export function registerHandler(name, handler) {
9
+ handlerRegistry.set(name, handler);
10
+ }
11
+ /**
12
+ * Get a registered handler by name
13
+ * @param name - Name of the action handler to retrieve
14
+ * @public
15
+ */
16
+ export function getHandler(name) {
17
+ return handlerRegistry.get(name);
18
+ }
19
+ /**
20
+ * Check if a handler is registered
21
+ * @param name - Name of the action handler to check
22
+ * @public
23
+ */
24
+ export function hasHandler(name) {
25
+ return handlerRegistry.has(name);
26
+ }
27
+ /**
28
+ * Clear all registered handlers
29
+ * @public
30
+ */
31
+ export function clearHandlers() {
32
+ handlerRegistry.clear();
33
+ }
34
+ // =============================================================================
35
+ // Built-in Handlers
36
+ // =============================================================================
37
+ /**
38
+ * Validate that all required fields are present in a record
39
+ */
40
+ const validateRequiredFields = async (args, context) => {
41
+ const [record] = args;
42
+ const { doctype } = context;
43
+ const missing = [];
44
+ for (const field of doctype.fields) {
45
+ if (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {
46
+ missing.push(field.label ?? field.fieldname);
47
+ }
48
+ }
49
+ if (missing.length > 0) {
50
+ throw new Error(`Missing required fields: ${missing.join(', ')}`);
51
+ }
52
+ return { valid: true };
53
+ };
54
+ /**
55
+ * Validate field types match expected types
56
+ */
57
+ const validateFieldTypes = async (args, context) => {
58
+ const [record] = args;
59
+ const { doctype } = context;
60
+ const errors = [];
61
+ for (const field of doctype.fields) {
62
+ const value = record[field.fieldname];
63
+ if (value === undefined || value === null)
64
+ continue;
65
+ const error = validateFieldValue(field.fieldname, value, field.fieldtype);
66
+ if (error)
67
+ errors.push(error);
68
+ }
69
+ if (errors.length > 0) {
70
+ throw new Error(`Field type validation failed:\n${errors.join('\n')}`);
71
+ }
72
+ return { valid: true };
73
+ };
74
+ /**
75
+ * Validate a single field value against its expected type
76
+ */
77
+ function validateFieldValue(fieldname, value, fieldtype) {
78
+ switch (fieldtype) {
79
+ case 'Int':
80
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
81
+ return `${fieldname}: expected integer, got ${typeof value}`;
82
+ }
83
+ break;
84
+ case 'Float':
85
+ case 'Decimal':
86
+ case 'Currency':
87
+ case 'Quantity':
88
+ if (typeof value !== 'number' && typeof value !== 'string') {
89
+ return `${fieldname}: expected number, got ${typeof value}`;
90
+ }
91
+ break;
92
+ case 'Check':
93
+ if (typeof value !== 'boolean') {
94
+ return `${fieldname}: expected boolean, got ${typeof value}`;
95
+ }
96
+ break;
97
+ case 'Data':
98
+ case 'Text':
99
+ case 'Code':
100
+ case 'Link':
101
+ if (typeof value !== 'string') {
102
+ return `${fieldname}: expected string, got ${typeof value}`;
103
+ }
104
+ break;
105
+ case 'Date':
106
+ case 'Time':
107
+ case 'Datetime':
108
+ if (typeof value !== 'string' && !(value instanceof Date)) {
109
+ return `${fieldname}: expected date string or Date, got ${typeof value}`;
110
+ }
111
+ break;
112
+ case 'JSON':
113
+ if (typeof value !== 'object') {
114
+ return `${fieldname}: expected object, got ${typeof value}`;
115
+ }
116
+ break;
117
+ case 'Table':
118
+ if (!Array.isArray(value)) {
119
+ return `${fieldname}: expected array, got ${typeof value}`;
120
+ }
121
+ break;
122
+ }
123
+ return null;
124
+ }
125
+ /**
126
+ * No-op handler for testing or placeholder actions
127
+ */
128
+ const noop = async () => {
129
+ return { ok: true };
130
+ };
131
+ /**
132
+ * Built-in handlers available for registration
133
+ * @public
134
+ */
135
+ export const builtinHandlers = {
136
+ validateRequiredFields,
137
+ validateFieldTypes,
138
+ noop,
139
+ };
140
+ /**
141
+ * Register all built-in handlers
142
+ * @public
143
+ */
144
+ export function registerBuiltinHandlers() {
145
+ for (const [name, handler] of Object.entries(builtinHandlers)) {
146
+ registerHandler(name, handler);
147
+ }
148
+ }
@@ -1,4 +1,4 @@
1
- import { DoctypeMeta, ValidationError } from '../types';
1
+ import type { DoctypeMeta, ValidationError } from '../types';
2
2
  /**
3
3
  * Error thrown when a doctype definition fails validation
4
4
  * @public
@@ -0,0 +1,167 @@
1
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseDoctype, validateDoctype } from '../types';
4
+ const doctypeRegistry = new Map();
5
+ /**
6
+ * Error thrown when a doctype definition fails validation
7
+ * @public
8
+ */
9
+ export class DoctypeValidationError extends Error {
10
+ file;
11
+ errors;
12
+ constructor(
13
+ /** File path or name where the validation error occurred */
14
+ file,
15
+ /** List of validation errors found */
16
+ errors) {
17
+ const errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\n');
18
+ super(`Invalid doctype definition in ${file}:\n${errorMessages}`);
19
+ this.file = file;
20
+ this.errors = errors;
21
+ this.name = 'DoctypeValidationError';
22
+ }
23
+ }
24
+ /**
25
+ * Load doctype definitions from a directory of JSON files
26
+ * @param dir - Directory path containing doctype JSON files
27
+ * @param options - Options for loading doctypes (continueOnError, onError callback)
28
+ * @public
29
+ */
30
+ export function loadDoctypes(dir, options = {}) {
31
+ const entries = readdirSync(dir);
32
+ for (const entry of entries) {
33
+ const fullPath = join(dir, entry);
34
+ const stat = statSync(fullPath);
35
+ if (stat.isDirectory()) {
36
+ loadDoctypes(fullPath, options);
37
+ }
38
+ else if (entry.endsWith('.json')) {
39
+ loadDoctypeFile(fullPath, options);
40
+ }
41
+ }
42
+ }
43
+ /**
44
+ * Load and validate a single doctype file
45
+ */
46
+ function loadDoctypeFile(filePath, options) {
47
+ const content = readFileSync(filePath, 'utf-8');
48
+ let data;
49
+ try {
50
+ data = JSON.parse(content);
51
+ }
52
+ catch (err) {
53
+ const parseError = {
54
+ path: [],
55
+ message: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,
56
+ };
57
+ if (options.continueOnError) {
58
+ options.onError?.(filePath, [parseError]);
59
+ return;
60
+ }
61
+ throw new DoctypeValidationError(filePath, [parseError]);
62
+ }
63
+ const result = validateDoctype(data);
64
+ if (!result.success) {
65
+ if (options.continueOnError) {
66
+ options.onError?.(filePath, result.errors);
67
+ return;
68
+ }
69
+ throw new DoctypeValidationError(filePath, result.errors);
70
+ }
71
+ const doctype = parseDoctype(data);
72
+ doctypeRegistry.set(doctype.name, doctype);
73
+ }
74
+ /**
75
+ * Load doctypes from an object (for programmatic use)
76
+ * @param doctypes - Object mapping doctype names to doctype definitions
77
+ * @param options - Options for loading doctypes (continueOnError, onError callback)
78
+ * @public
79
+ */
80
+ export function loadDoctypesFromObject(doctypes, options = {}) {
81
+ for (const [name, data] of Object.entries(doctypes)) {
82
+ const withName = { ...data, name };
83
+ const result = validateDoctype(withName);
84
+ if (!result.success) {
85
+ if (options.continueOnError) {
86
+ options.onError?.(name, result.errors);
87
+ continue;
88
+ }
89
+ throw new DoctypeValidationError(name, result.errors);
90
+ }
91
+ const doctype = parseDoctype(withName);
92
+ doctypeRegistry.set(doctype.name, doctype);
93
+ }
94
+ }
95
+ /**
96
+ * Get a doctype by name
97
+ * @param name - Name of the doctype to retrieve
98
+ * @public
99
+ */
100
+ export function getMeta(name) {
101
+ return doctypeRegistry.get(name);
102
+ }
103
+ /**
104
+ * Get all loaded doctypes
105
+ * @public
106
+ */
107
+ export function getAllMeta() {
108
+ return Array.from(doctypeRegistry.values());
109
+ }
110
+ /**
111
+ * Check if a doctype is registered
112
+ * @param name - Name of the doctype to check
113
+ * @public
114
+ */
115
+ export function hasMeta(name) {
116
+ return doctypeRegistry.has(name);
117
+ }
118
+ /**
119
+ * Clear all registered doctypes
120
+ * @public
121
+ */
122
+ export function clearRegistry() {
123
+ doctypeRegistry.clear();
124
+ }
125
+ /**
126
+ * Validate cross-doctype references (Link fields, inherits, etc.)
127
+ * Call after all doctypes are loaded.
128
+ * @public
129
+ */
130
+ export function validateReferences() {
131
+ const errors = [];
132
+ for (const doctype of doctypeRegistry.values()) {
133
+ // Check inherits reference
134
+ if (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {
135
+ errors.push({
136
+ path: [doctype.name, 'inherits'],
137
+ message: `References unknown doctype: ${doctype.inherits}`,
138
+ });
139
+ }
140
+ // Check listDoctype reference
141
+ if (doctype.listDoctype && !doctypeRegistry.has(doctype.listDoctype)) {
142
+ errors.push({
143
+ path: [doctype.name, 'listDoctype'],
144
+ message: `References unknown doctype: ${doctype.listDoctype}`,
145
+ });
146
+ }
147
+ // Check parentDoctype reference
148
+ if (doctype.parentDoctype && !doctypeRegistry.has(doctype.parentDoctype)) {
149
+ errors.push({
150
+ path: [doctype.name, 'parentDoctype'],
151
+ message: `References unknown doctype: ${doctype.parentDoctype}`,
152
+ });
153
+ }
154
+ // Check Link field targets
155
+ for (const field of doctype.fields) {
156
+ if (field.fieldtype === 'Link' && typeof field.options === 'string') {
157
+ if (!doctypeRegistry.has(field.options)) {
158
+ errors.push({
159
+ path: [doctype.name, 'fields', field.fieldname, 'options'],
160
+ message: `Link references unknown doctype: ${field.options}`,
161
+ });
162
+ }
163
+ }
164
+ }
165
+ }
166
+ return errors;
167
+ }
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.57.0"
9
+ }
10
+ ]
11
+ }
@@ -1,6 +1,6 @@
1
- import { DoctypeMeta } from '@stonecrop/schema';
2
1
  export { StonecropFieldType, FieldOptions, FieldMeta, ActionDefinition, WorkflowMeta, DoctypeMeta, validateDoctype, validateField, parseDoctype, parseField, } from '@stonecrop/schema';
3
2
  export type { ValidationResult, ValidationError, IntrospectionSource, GraphQLConversionOptions, GraphQLConversionFieldMeta, ConvertedGraphQLDoctype, } from '@stonecrop/schema';
3
+ import type { DoctypeMeta } from '@stonecrop/schema';
4
4
  /**
5
5
  * Route context for identifying what doctype/record we're working with
6
6
  * @public
@@ -0,0 +1,2 @@
1
+ // Re-export all schema types from @stonecrop/schema for backward compatibility
2
+ export { StonecropFieldType, FieldOptions, FieldMeta, ActionDefinition, WorkflowMeta, DoctypeMeta, validateDoctype, validateField, parseDoctype, parseField, } from '@stonecrop/schema';
@@ -0,0 +1,4 @@
1
+ import { describe, it } from 'vitest';
2
+ describe('Registry Tests', () => {
3
+ it.todo('should implement registry tests');
4
+ });
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
7
+ "types": "./dist/src/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
- "types": "./dist/index.d.ts",
10
+ "types": "./dist/src/index.d.ts",
11
11
  "import": "./dist/index.js",
12
12
  "require": "./dist/index.cjs"
13
13
  }
@@ -18,14 +18,13 @@
18
18
  "dependencies": {
19
19
  "graphql": "^16.12.0",
20
20
  "postgraphile": "^5.0.0-rc.7",
21
- "@stonecrop/schema": "0.8.8"
21
+ "@stonecrop/schema": "0.8.9"
22
22
  },
23
23
  "devDependencies": {
24
- "@rushstack/heft": "^1.1.7",
24
+ "@rushstack/heft": "^1.2.0",
25
25
  "@types/node": "^22.19.5",
26
26
  "typescript": "^5.9.3",
27
27
  "vite": "^7.3.1",
28
- "vite-plugin-dts": "^4.5.4",
29
28
  "vitest": "^4.0.18",
30
29
  "stonecrop-rig": "0.7.0"
31
30
  },
package/dist/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './src/index'
2
- export {}