@stonecrop/graphql-middleware 0.11.0 → 0.11.2
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 +59 -63
- package/dist/graphql-middleware.d.ts +165 -0
- package/dist/index.js +422 -225
- package/dist/index.js.map +1 -1
- package/dist/plugin/postgraphile.js +216 -20
- package/dist/src/index.d.ts +4 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/plugin/postgraphile.d.ts +56 -16
- package/dist/src/plugin/postgraphile.d.ts.map +1 -1
- package/dist/src/typeDefs.d.ts +7 -0
- package/dist/src/typeDefs.d.ts.map +1 -0
- package/dist/src/types/index.d.ts +1 -0
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/src/types/query.d.ts +130 -0
- package/dist/src/types/query.d.ts.map +1 -0
- package/dist/typeDefs.js +79 -0
- package/dist/{src/types/index.js → types/query.js} +1 -1
- package/package.json +2 -2
- package/dist/index.cjs +0 -86
- package/dist/index.cjs.map +0 -1
- package/dist/src/index.js +0 -8
- package/dist/src/plugin/postgraphile.js +0 -381
- package/dist/src/registry/actions.js +0 -156
- package/dist/src/registry/doctypes.js +0 -167
- package/dist/src/tsdoc-metadata.json +0 -11
|
@@ -1,381 +0,0 @@
|
|
|
1
|
-
import { snakeToCamel, toPascalCase } from '@stonecrop/schema';
|
|
2
|
-
import { constant, lambda, object, loadOne } from 'postgraphile/grafast';
|
|
3
|
-
import { extendSchema, gql } from 'postgraphile/utils';
|
|
4
|
-
import pluralize from 'pluralize';
|
|
5
|
-
import { getHandler } from '../registry/actions';
|
|
6
|
-
import { getMeta, getAllMeta } from '../registry/doctypes';
|
|
7
|
-
/**
|
|
8
|
-
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
|
|
9
|
-
* @param options - Plugin configuration options
|
|
10
|
-
* @returns A PostGraphile plugin
|
|
11
|
-
* @public
|
|
12
|
-
*/
|
|
13
|
-
export const createStonecropPlugin = (options) => {
|
|
14
|
-
// Resolve inflection callbacks with Amber defaults
|
|
15
|
-
const recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName;
|
|
16
|
-
const connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName;
|
|
17
|
-
const orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName;
|
|
18
|
-
const recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName;
|
|
19
|
-
const recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType;
|
|
20
|
-
return extendSchema(() => {
|
|
21
|
-
return {
|
|
22
|
-
typeDefs: gql `
|
|
23
|
-
type StonecropFieldMeta {
|
|
24
|
-
fieldname: String!
|
|
25
|
-
fieldtype: String!
|
|
26
|
-
component: String
|
|
27
|
-
label: String
|
|
28
|
-
width: String
|
|
29
|
-
align: String
|
|
30
|
-
required: Boolean
|
|
31
|
-
readOnly: Boolean
|
|
32
|
-
edit: Boolean
|
|
33
|
-
hidden: Boolean
|
|
34
|
-
default: JSON
|
|
35
|
-
options: JSON
|
|
36
|
-
mask: String
|
|
37
|
-
precision: Int
|
|
38
|
-
scale: Int
|
|
39
|
-
mode: String
|
|
40
|
-
validation: JSON
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
type StonecropActionDefinition {
|
|
44
|
-
label: String!
|
|
45
|
-
handler: String!
|
|
46
|
-
requiredFields: [String!]
|
|
47
|
-
allowedStates: [String!]
|
|
48
|
-
confirm: Boolean
|
|
49
|
-
args: JSON
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
type StonecropWorkflowMeta {
|
|
53
|
-
states: [String!]
|
|
54
|
-
actions: JSON
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
type StonecropDoctypeMeta {
|
|
58
|
-
name: String!
|
|
59
|
-
slug: String
|
|
60
|
-
tableName: String
|
|
61
|
-
fields: [StonecropFieldMeta!]!
|
|
62
|
-
workflow: StonecropWorkflowMeta
|
|
63
|
-
inherits: String
|
|
64
|
-
listDoctype: String
|
|
65
|
-
parentDoctype: String
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
type StonecropRecordResult {
|
|
69
|
-
data: JSON
|
|
70
|
-
doctype: String!
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
type StonecropRecordsResult {
|
|
74
|
-
data: [JSON!]!
|
|
75
|
-
doctype: String!
|
|
76
|
-
count: Int!
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
type StonecropActionResult {
|
|
80
|
-
success: Boolean!
|
|
81
|
-
data: JSON
|
|
82
|
-
error: String
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
extend type Query {
|
|
86
|
-
stonecropMeta(doctype: String!): StonecropDoctypeMeta
|
|
87
|
-
stonecropAllMeta: [StonecropDoctypeMeta!]!
|
|
88
|
-
stonecropRecord(doctype: String!, id: String!): StonecropRecordResult
|
|
89
|
-
stonecropRecords(
|
|
90
|
-
doctype: String!
|
|
91
|
-
filters: JSON
|
|
92
|
-
orderBy: String
|
|
93
|
-
limit: Int
|
|
94
|
-
offset: Int
|
|
95
|
-
): StonecropRecordsResult
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
extend type Mutation {
|
|
99
|
-
stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
|
|
100
|
-
}
|
|
101
|
-
`,
|
|
102
|
-
objects: {
|
|
103
|
-
Query: {
|
|
104
|
-
plans: {
|
|
105
|
-
stonecropMeta(_, { $doctype }) {
|
|
106
|
-
return lambda($doctype, (doctype) => {
|
|
107
|
-
const meta = getMeta(doctype);
|
|
108
|
-
return meta ?? null;
|
|
109
|
-
});
|
|
110
|
-
},
|
|
111
|
-
stonecropAllMeta() {
|
|
112
|
-
return constant(getAllMeta());
|
|
113
|
-
},
|
|
114
|
-
stonecropRecord(_, { $doctype, $id }) {
|
|
115
|
-
return loadOne(object({ doctype: $doctype, id: $id }), async (specs) => {
|
|
116
|
-
return await Promise.all(specs.map(async (spec) => {
|
|
117
|
-
const meta = getMeta(spec.doctype);
|
|
118
|
-
if (!meta) {
|
|
119
|
-
throw new Error(`Unknown doctype: ${spec.doctype}`);
|
|
120
|
-
}
|
|
121
|
-
if (!meta.tableName) {
|
|
122
|
-
throw new Error(`Doctype ${spec.doctype} has no table mapping`);
|
|
123
|
-
}
|
|
124
|
-
const query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType);
|
|
125
|
-
const result = await options.executor.query(query, {
|
|
126
|
-
[recordArgName(meta.tableName)]: spec.id,
|
|
127
|
-
});
|
|
128
|
-
return {
|
|
129
|
-
data: extractSingleResult(result, meta, recordFieldName),
|
|
130
|
-
doctype: spec.doctype,
|
|
131
|
-
};
|
|
132
|
-
}));
|
|
133
|
-
});
|
|
134
|
-
},
|
|
135
|
-
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
|
|
136
|
-
return loadOne(object({
|
|
137
|
-
doctype: $doctype,
|
|
138
|
-
filters: $filters,
|
|
139
|
-
orderBy: $orderBy,
|
|
140
|
-
limit: $limit,
|
|
141
|
-
offset: $offset,
|
|
142
|
-
}), async (specs) => {
|
|
143
|
-
return await Promise.all(specs.map(async (spec) => {
|
|
144
|
-
const meta = getMeta(spec.doctype);
|
|
145
|
-
if (!meta) {
|
|
146
|
-
throw new Error(`Unknown doctype: ${spec.doctype}`);
|
|
147
|
-
}
|
|
148
|
-
if (!meta.tableName) {
|
|
149
|
-
throw new Error(`Doctype ${spec.doctype} has no table mapping`);
|
|
150
|
-
}
|
|
151
|
-
const query = buildListQuery(meta, {
|
|
152
|
-
limit: spec.limit,
|
|
153
|
-
offset: spec.offset,
|
|
154
|
-
orderBy: spec.orderBy,
|
|
155
|
-
}, connectionFieldName, orderByTypeName);
|
|
156
|
-
const result = await options.executor.query(query, {
|
|
157
|
-
limit: spec.limit,
|
|
158
|
-
offset: spec.offset,
|
|
159
|
-
orderBy: spec.orderBy,
|
|
160
|
-
});
|
|
161
|
-
const data = extractListResult(result, meta, connectionFieldName);
|
|
162
|
-
return {
|
|
163
|
-
data,
|
|
164
|
-
doctype: spec.doctype,
|
|
165
|
-
count: data.length,
|
|
166
|
-
};
|
|
167
|
-
}));
|
|
168
|
-
});
|
|
169
|
-
},
|
|
170
|
-
},
|
|
171
|
-
},
|
|
172
|
-
Mutation: {
|
|
173
|
-
plans: {
|
|
174
|
-
stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
|
|
175
|
-
return loadOne(object({
|
|
176
|
-
doctype: $doctype,
|
|
177
|
-
action: $action,
|
|
178
|
-
actionArgs: $actionArgs,
|
|
179
|
-
}), async (specs) => {
|
|
180
|
-
return await Promise.all(specs.map(async (spec) => {
|
|
181
|
-
const meta = getMeta(spec.doctype);
|
|
182
|
-
if (!meta) {
|
|
183
|
-
return {
|
|
184
|
-
success: false,
|
|
185
|
-
data: null,
|
|
186
|
-
error: `Unknown doctype: ${spec.doctype}`,
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
const actionDef = meta.workflow?.actions?.[spec.action];
|
|
190
|
-
if (!actionDef) {
|
|
191
|
-
return {
|
|
192
|
-
success: false,
|
|
193
|
-
data: null,
|
|
194
|
-
error: `Unknown action: ${spec.action} on ${spec.doctype}`,
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
const handlerName = actionDef.handler;
|
|
198
|
-
const handler = getHandler(handlerName);
|
|
199
|
-
if (!handler) {
|
|
200
|
-
return {
|
|
201
|
-
success: false,
|
|
202
|
-
data: null,
|
|
203
|
-
error: `Handler not registered: ${handlerName}`,
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
const actionContext = {
|
|
207
|
-
doctype: meta,
|
|
208
|
-
executor: options.executor,
|
|
209
|
-
};
|
|
210
|
-
try {
|
|
211
|
-
const result = await handler(spec.actionArgs ?? [], actionContext);
|
|
212
|
-
return {
|
|
213
|
-
success: true,
|
|
214
|
-
data: result,
|
|
215
|
-
error: null,
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
catch (err) {
|
|
219
|
-
return {
|
|
220
|
-
success: false,
|
|
221
|
-
data: null,
|
|
222
|
-
error: err instanceof Error ? err.message : String(err),
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
}));
|
|
226
|
-
});
|
|
227
|
-
},
|
|
228
|
-
},
|
|
229
|
-
},
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
});
|
|
233
|
-
};
|
|
234
|
-
// =============================================================================
|
|
235
|
-
// Inflection helpers — default to PostGraphile Amber preset conventions
|
|
236
|
-
// Uses `pluralize` for proper English singularization (handles irregular
|
|
237
|
-
// plurals like statuses→status, categories→category, addresses→address).
|
|
238
|
-
// snakeToCamel / toPascalCase are imported from @stonecrop/schema.
|
|
239
|
-
// =============================================================================
|
|
240
|
-
/**
|
|
241
|
-
* Amber default: sales_orders → salesOrderById
|
|
242
|
-
* Uses `pluralize` for proper singularization of irregular plurals.
|
|
243
|
-
* Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
|
|
244
|
-
* @public
|
|
245
|
-
*/
|
|
246
|
-
function defaultRecordFieldName(tableName) {
|
|
247
|
-
const singular = pluralize.singular(tableName);
|
|
248
|
-
return `${snakeToCamel(singular)}ById`;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Amber default: sales_orders → allSalesOrders
|
|
252
|
-
* @public
|
|
253
|
-
*/
|
|
254
|
-
function defaultConnectionFieldName(tableName) {
|
|
255
|
-
return `all${toPascalCase(tableName)}`;
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* Amber default: sales_orders → SalesOrdersOrderBy
|
|
259
|
-
* @public
|
|
260
|
-
*/
|
|
261
|
-
function defaultOrderByTypeName(tableName) {
|
|
262
|
-
return `${toPascalCase(tableName)}OrderBy`;
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Default PK argument name: 'id' (standard Relay Global ID pattern).
|
|
266
|
-
* Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
|
|
267
|
-
* PostGraphile Amber generates `rowId: UUID!` for those fields.
|
|
268
|
-
* @public
|
|
269
|
-
*/
|
|
270
|
-
function defaultRecordArgName(_tableName) {
|
|
271
|
-
return 'id';
|
|
272
|
-
}
|
|
273
|
-
/**
|
|
274
|
-
* Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
|
|
275
|
-
* Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
|
|
276
|
-
* such as integer serials or Relay Global IDs ('ID!').
|
|
277
|
-
* @public
|
|
278
|
-
*/
|
|
279
|
-
function defaultRecordArgType(_tableName) {
|
|
280
|
-
return 'UUID!';
|
|
281
|
-
}
|
|
282
|
-
// =============================================================================
|
|
283
|
-
// Query builders — generate GraphQL queries to send to the underlying schema
|
|
284
|
-
// =============================================================================
|
|
285
|
-
/**
|
|
286
|
-
* Fieldtypes that map to GraphQL object/connection types and require sub-selections.
|
|
287
|
-
* These fields are excluded from generated query field selections.
|
|
288
|
-
* @public
|
|
289
|
-
*/
|
|
290
|
-
const RELATION_FIELDTYPES = new Set(['Link', 'Doctype']);
|
|
291
|
-
/**
|
|
292
|
-
* Filter fields to only those directly queryable as scalars, excluding Link and Doctype
|
|
293
|
-
* relation fields that require GraphQL sub-selections.
|
|
294
|
-
* @public
|
|
295
|
-
*/
|
|
296
|
-
function queryableFieldNames(meta) {
|
|
297
|
-
return meta.fields
|
|
298
|
-
.filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))
|
|
299
|
-
.map(f => f.fieldname)
|
|
300
|
-
.join('\n ');
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* Build a GraphQL query to fetch a single record by ID.
|
|
304
|
-
* Excludes Link and Doctype relation fields from the selection set.
|
|
305
|
-
* The PK argument name and type are configurable via `StonecropInflectionConfig.recordArgName`
|
|
306
|
-
* and `StonecropInflectionConfig.recordArgType` to match the target schema's conventions
|
|
307
|
-
* (e.g. `rowId: UUID!` for PostGraphile Amber with row_id columns).
|
|
308
|
-
* @public
|
|
309
|
-
*/
|
|
310
|
-
function buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType) {
|
|
311
|
-
const fieldNames = queryableFieldNames(meta);
|
|
312
|
-
const queryName = recordFieldName(meta.tableName);
|
|
313
|
-
const argName = recordArgName(meta.tableName);
|
|
314
|
-
const argType = recordArgType(meta.tableName);
|
|
315
|
-
return `
|
|
316
|
-
query GetRecord($${argName}: ${argType}) {
|
|
317
|
-
${queryName}(${argName}: $${argName}) {
|
|
318
|
-
${fieldNames}
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
`;
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Build a GraphQL connection query to fetch a list of records.
|
|
325
|
-
* Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
|
|
326
|
-
* avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
|
|
327
|
-
* Excludes Link and Doctype relation fields from the selection set.
|
|
328
|
-
* @public
|
|
329
|
-
*/
|
|
330
|
-
function buildListQuery(meta, args, connectionFieldName, orderByTypeName) {
|
|
331
|
-
const fieldNames = queryableFieldNames(meta);
|
|
332
|
-
const connectionName = connectionFieldName(meta.tableName);
|
|
333
|
-
const orderByType = orderByTypeName(meta.tableName);
|
|
334
|
-
const varDecls = [];
|
|
335
|
-
const queryArgs = [];
|
|
336
|
-
if (args.limit) {
|
|
337
|
-
varDecls.push('$limit: Int');
|
|
338
|
-
queryArgs.push(`first: $limit`);
|
|
339
|
-
}
|
|
340
|
-
if (args.offset) {
|
|
341
|
-
varDecls.push('$offset: Int');
|
|
342
|
-
queryArgs.push(`offset: $offset`);
|
|
343
|
-
}
|
|
344
|
-
if (args.orderBy) {
|
|
345
|
-
varDecls.push(`$orderBy: [${orderByType}!]`);
|
|
346
|
-
queryArgs.push(`orderBy: $orderBy`);
|
|
347
|
-
}
|
|
348
|
-
const varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : '';
|
|
349
|
-
const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : '';
|
|
350
|
-
return `
|
|
351
|
-
query GetRecords${varStr} {
|
|
352
|
-
${connectionName}${argsStr} {
|
|
353
|
-
nodes {
|
|
354
|
-
${fieldNames}
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
`;
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* Extract a single record from a PostGraphile query result using the record field name.
|
|
362
|
-
* @internal
|
|
363
|
-
*/
|
|
364
|
-
function extractSingleResult(result, meta, recordFieldName) {
|
|
365
|
-
const queryName = recordFieldName(meta.tableName);
|
|
366
|
-
return result[queryName];
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* Extract the list of nodes from a PostGraphile connection query result.
|
|
370
|
-
* Returns an empty array if the connection field is absent.
|
|
371
|
-
* @internal
|
|
372
|
-
*/
|
|
373
|
-
function extractListResult(result, meta, connectionFieldName) {
|
|
374
|
-
const connectionName = connectionFieldName(meta.tableName);
|
|
375
|
-
const connection = result[connectionName];
|
|
376
|
-
return connection?.nodes ?? [];
|
|
377
|
-
}
|
|
378
|
-
// =============================================================================
|
|
379
|
-
// Exported for testing and advanced usage
|
|
380
|
-
// =============================================================================
|
|
381
|
-
export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, extractSingleResult, extractListResult, };
|
|
@@ -1,156 +0,0 @@
|
|
|
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, value);
|
|
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(field, value) {
|
|
78
|
-
const { fieldname, fieldtype, cardinality } = field;
|
|
79
|
-
switch (fieldtype) {
|
|
80
|
-
case 'Int':
|
|
81
|
-
if (typeof value !== 'number' || !Number.isInteger(value)) {
|
|
82
|
-
return `${fieldname}: expected integer, got ${typeof value}`;
|
|
83
|
-
}
|
|
84
|
-
break;
|
|
85
|
-
case 'Float':
|
|
86
|
-
case 'Decimal':
|
|
87
|
-
case 'Currency':
|
|
88
|
-
case 'Quantity':
|
|
89
|
-
if (typeof value !== 'number' && typeof value !== 'string') {
|
|
90
|
-
return `${fieldname}: expected number, got ${typeof value}`;
|
|
91
|
-
}
|
|
92
|
-
break;
|
|
93
|
-
case 'Check':
|
|
94
|
-
if (typeof value !== 'boolean') {
|
|
95
|
-
return `${fieldname}: expected boolean, got ${typeof value}`;
|
|
96
|
-
}
|
|
97
|
-
break;
|
|
98
|
-
case 'Data':
|
|
99
|
-
case 'Text':
|
|
100
|
-
case 'Code':
|
|
101
|
-
case 'Link':
|
|
102
|
-
if (typeof value !== 'string') {
|
|
103
|
-
return `${fieldname}: expected string, got ${typeof value}`;
|
|
104
|
-
}
|
|
105
|
-
break;
|
|
106
|
-
case 'Date':
|
|
107
|
-
case 'Time':
|
|
108
|
-
case 'Datetime':
|
|
109
|
-
if (typeof value !== 'string' && !(value instanceof Date)) {
|
|
110
|
-
return `${fieldname}: expected date string or Date, got ${typeof value}`;
|
|
111
|
-
}
|
|
112
|
-
break;
|
|
113
|
-
case 'JSON':
|
|
114
|
-
if (typeof value !== 'object') {
|
|
115
|
-
return `${fieldname}: expected object, got ${typeof value}`;
|
|
116
|
-
}
|
|
117
|
-
break;
|
|
118
|
-
case 'Doctype':
|
|
119
|
-
if (cardinality === 'many') {
|
|
120
|
-
if (!Array.isArray(value)) {
|
|
121
|
-
return `${fieldname}: expected array, got ${typeof value}`;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
else {
|
|
125
|
-
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
126
|
-
return `${fieldname}: expected object, got ${typeof value}`;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
break;
|
|
130
|
-
}
|
|
131
|
-
return null;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* No-op handler for testing or placeholder actions
|
|
135
|
-
*/
|
|
136
|
-
const noop = async () => {
|
|
137
|
-
return { ok: true };
|
|
138
|
-
};
|
|
139
|
-
/**
|
|
140
|
-
* Built-in handlers available for registration
|
|
141
|
-
* @public
|
|
142
|
-
*/
|
|
143
|
-
export const builtinHandlers = {
|
|
144
|
-
validateRequiredFields,
|
|
145
|
-
validateFieldTypes,
|
|
146
|
-
noop,
|
|
147
|
-
};
|
|
148
|
-
/**
|
|
149
|
-
* Register all built-in handlers
|
|
150
|
-
* @public
|
|
151
|
-
*/
|
|
152
|
-
export function registerBuiltinHandlers() {
|
|
153
|
-
for (const [name, handler] of Object.entries(builtinHandlers)) {
|
|
154
|
-
registerHandler(name, handler);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { parseDoctype, validateDoctype } from '@stonecrop/schema';
|
|
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
|
-
}
|