@demokit-ai/core 0.1.0 → 0.3.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/dist/index.d.cts CHANGED
@@ -263,6 +263,134 @@ interface ParsedPattern {
263
263
  */
264
264
  paramNames: string[];
265
265
  }
266
+ /**
267
+ * Configuration for fetching fixtures from DemoKit Cloud
268
+ */
269
+ interface RemoteConfig {
270
+ /**
271
+ * DemoKit Cloud API key
272
+ * Format: dk_live_xxxx
273
+ */
274
+ apiKey: string;
275
+ /**
276
+ * DemoKit Cloud API URL
277
+ * @default 'https://api.demokit.cloud'
278
+ */
279
+ cloudUrl?: string;
280
+ /**
281
+ * Error callback for remote fetch failures
282
+ */
283
+ onError?: (error: Error) => void;
284
+ /**
285
+ * Callback when fixtures are successfully loaded
286
+ */
287
+ onLoad?: (response: CloudFixtureResponse) => void;
288
+ /**
289
+ * Timeout for API requests in milliseconds
290
+ * @default 10000
291
+ */
292
+ timeout?: number;
293
+ /**
294
+ * Whether to retry on failure
295
+ * @default true
296
+ */
297
+ retry?: boolean;
298
+ /**
299
+ * Maximum number of retries
300
+ * @default 3
301
+ */
302
+ maxRetries?: number;
303
+ }
304
+ /**
305
+ * Response from DemoKit Cloud /api/v1/fixtures endpoint
306
+ */
307
+ interface CloudFixtureResponse {
308
+ /**
309
+ * The generated fixture data (keyed by model name)
310
+ * @example { users: [{ id: '1', name: 'Alice' }], products: [...] }
311
+ */
312
+ data: Record<string, unknown[]>;
313
+ /**
314
+ * Endpoint-to-data mappings for SDK auto-configuration
315
+ */
316
+ mappings: EndpointMapping[];
317
+ /**
318
+ * Version identifier (generation ID) for cache invalidation
319
+ */
320
+ version: string;
321
+ }
322
+ /**
323
+ * An endpoint mapping that describes how to route API calls to fixture data
324
+ */
325
+ interface EndpointMapping {
326
+ /**
327
+ * HTTP method (GET, POST, PUT, PATCH, DELETE)
328
+ */
329
+ method: string;
330
+ /**
331
+ * URL pattern with :param placeholders
332
+ * @example '/api/users/:id'
333
+ */
334
+ pattern: string;
335
+ /**
336
+ * Key in fixture data to use as source
337
+ * @example 'users'
338
+ */
339
+ sourceModel: string;
340
+ /**
341
+ * Response type:
342
+ * - 'collection': Returns all records (array)
343
+ * - 'single': Returns one record by lookup
344
+ * - 'custom': Uses custom transform (not yet supported in SDK)
345
+ */
346
+ responseType: 'collection' | 'single' | 'custom';
347
+ /**
348
+ * For 'single' type: field in data to match against
349
+ * @example 'id'
350
+ */
351
+ lookupField?: string | null;
352
+ /**
353
+ * For 'single' type: URL param name to use for lookup
354
+ * @example 'id' (from :id in pattern)
355
+ */
356
+ lookupParam?: string | null;
357
+ }
358
+ /**
359
+ * Combined configuration for DemoKit with optional remote support
360
+ */
361
+ interface DemoKitRemoteConfig extends Omit<DemoKitConfig, 'fixtures'> {
362
+ /**
363
+ * Remote configuration for fetching from DemoKit Cloud
364
+ * When provided, fixtures are fetched from the cloud
365
+ */
366
+ remote: RemoteConfig;
367
+ /**
368
+ * Local fixture overrides that take precedence over remote fixtures
369
+ * Useful for customizing specific endpoints while using cloud data for the rest
370
+ */
371
+ fixtures?: FixtureMap;
372
+ }
373
+ /**
374
+ * State of remote fixture loading
375
+ */
376
+ interface RemoteLoadingState {
377
+ /**
378
+ * Whether fixtures are currently being loaded
379
+ */
380
+ isLoading: boolean;
381
+ /**
382
+ * Error if loading failed
383
+ */
384
+ error: Error | null;
385
+ /**
386
+ * The loaded response (if successful)
387
+ */
388
+ response: CloudFixtureResponse | null;
389
+ /**
390
+ * Timestamp of last successful load
391
+ */
392
+ loadedAt: Date | null;
393
+ }
266
394
 
267
395
  /**
268
396
  * Create a demo interceptor that patches fetch to return mock data
@@ -562,4 +690,2189 @@ declare function saveDemoState(key: string | undefined, enabled: boolean): void;
562
690
  */
563
691
  declare function clearDemoState(key?: string): void;
564
692
 
565
- export { DEFAULT_STORAGE_KEY, type DemoInterceptor, type DemoKitConfig, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type FixtureHandler, type FixtureMap, type MatchResult, type ParsedPattern, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type RequestContext, type SessionState, clearDemoState, clearPatternCache, createDemoInterceptor, createDemoState, createDemoStateStore, createSessionState, findMatchingPattern, findMatchingQueryKeyPattern, loadDemoState, matchQueryKey, matchUrl, parseUrlPattern, saveDemoState };
693
+ /**
694
+ * Remote Configuration Support for DemoKit Cloud
695
+ *
696
+ * Provides functions to fetch fixture data and endpoint mappings from DemoKit Cloud
697
+ * and transform them into FixtureMap handlers that can be used with the demo interceptor.
698
+ *
699
+ * @example
700
+ * ```typescript
701
+ * import { fetchCloudFixtures, buildFixtureMap } from '@demokit-ai/core'
702
+ *
703
+ * const response = await fetchCloudFixtures({
704
+ * apiKey: 'dk_live_xxx',
705
+ * })
706
+ *
707
+ * const fixtureMap = buildFixtureMap(response.data, response.mappings)
708
+ * ```
709
+ */
710
+
711
+ /**
712
+ * Default DemoKit Cloud API URL
713
+ */
714
+ declare const DEFAULT_CLOUD_URL = "https://api.demokit.cloud";
715
+ /**
716
+ * Default request timeout in milliseconds
717
+ */
718
+ declare const DEFAULT_TIMEOUT = 10000;
719
+ /**
720
+ * Default maximum retries
721
+ */
722
+ declare const DEFAULT_MAX_RETRIES = 3;
723
+ /**
724
+ * Validate API key format
725
+ */
726
+ declare function isValidApiKey(apiKey: string): boolean;
727
+ /**
728
+ * Error thrown when remote fetch fails
729
+ */
730
+ declare class RemoteFetchError extends Error {
731
+ readonly statusCode?: number | undefined;
732
+ readonly retryable: boolean;
733
+ constructor(message: string, statusCode?: number | undefined, retryable?: boolean);
734
+ }
735
+ /**
736
+ * Fetch fixtures and mappings from DemoKit Cloud
737
+ *
738
+ * @param config - Remote configuration with API key and options
739
+ * @returns Promise resolving to cloud fixture response with data, mappings, and version
740
+ * @throws RemoteFetchError if the request fails
741
+ *
742
+ * @example
743
+ * ```typescript
744
+ * const response = await fetchCloudFixtures({
745
+ * apiKey: 'dk_live_xxx',
746
+ * onLoad: (data) => console.log('Loaded version:', data.version),
747
+ * onError: (error) => console.error('Failed to load:', error),
748
+ * })
749
+ * ```
750
+ */
751
+ declare function fetchCloudFixtures(config: RemoteConfig): Promise<CloudFixtureResponse>;
752
+ /**
753
+ * Build a FixtureMap from cloud data and endpoint mappings
754
+ *
755
+ * Transforms endpoint mappings into fixture handlers that can be used
756
+ * with the demo interceptor. Each mapping becomes a pattern-matched
757
+ * handler that returns the appropriate data.
758
+ *
759
+ * @param data - Fixture data keyed by model name (e.g., { users: [...], products: [...] })
760
+ * @param mappings - Endpoint mappings from DemoKit Cloud
761
+ * @returns FixtureMap that can be passed to createDemoInterceptor
762
+ *
763
+ * @example
764
+ * ```typescript
765
+ * const fixtureMap = buildFixtureMap(
766
+ * { users: [{ id: '1', name: 'Alice' }] },
767
+ * [
768
+ * { method: 'GET', pattern: '/api/users', sourceModel: 'users', responseType: 'collection' },
769
+ * { method: 'GET', pattern: '/api/users/:id', sourceModel: 'users', responseType: 'single', lookupField: 'id', lookupParam: 'id' },
770
+ * ]
771
+ * )
772
+ *
773
+ * // Result:
774
+ * // {
775
+ * // 'GET /api/users': () => [{ id: '1', name: 'Alice' }],
776
+ * // 'GET /api/users/:id': ({ params }) => users.find(u => u.id === params.id),
777
+ * // }
778
+ * ```
779
+ */
780
+ declare function buildFixtureMap(data: Record<string, unknown[]>, mappings: EndpointMapping[]): FixtureMap;
781
+ /**
782
+ * Create a fixture handler for a single endpoint mapping
783
+ *
784
+ * @param mapping - The endpoint mapping configuration
785
+ * @param sourceData - The source data array for this mapping
786
+ * @returns A fixture handler function or undefined if mapping is invalid
787
+ */
788
+ declare function createHandlerForMapping(mapping: EndpointMapping, sourceData: unknown[]): FixtureHandler | undefined;
789
+ /**
790
+ * Merge remote fixtures with local overrides
791
+ *
792
+ * Creates a combined FixtureMap where local fixtures take precedence
793
+ * over remote fixtures for the same patterns.
794
+ *
795
+ * @param remoteFixtures - Fixtures built from cloud mappings
796
+ * @param localOverrides - Local fixtures that override remote ones
797
+ * @returns Merged FixtureMap
798
+ *
799
+ * @example
800
+ * ```typescript
801
+ * const merged = mergeFixtures(remoteFixtures, {
802
+ * // Override specific endpoint with custom logic
803
+ * 'POST /api/users': ({ body }) => ({ id: 'custom', ...body }),
804
+ * })
805
+ * ```
806
+ */
807
+ declare function mergeFixtures(remoteFixtures: FixtureMap, localOverrides?: FixtureMap): FixtureMap;
808
+ /**
809
+ * Create a complete fixture setup from cloud response and optional overrides
810
+ *
811
+ * Convenience function that combines buildFixtureMap and mergeFixtures.
812
+ *
813
+ * @param response - Cloud fixture response
814
+ * @param localOverrides - Optional local fixtures to merge
815
+ * @returns Complete FixtureMap ready for use with createDemoInterceptor
816
+ */
817
+ declare function createRemoteFixtures(response: CloudFixtureResponse, localOverrides?: FixtureMap): FixtureMap;
818
+
819
+ /**
820
+ * Core types for DemoKit schema representation
821
+ *
822
+ * These types represent a parsed API schema with relationship detection,
823
+ * independent of the source format (OpenAPI, GraphQL, etc.)
824
+ */
825
+ /**
826
+ * The main schema representation for DemoKit
827
+ * Contains all information needed for fixture generation
828
+ */
829
+ interface DemokitSchema {
830
+ /**
831
+ * Metadata about the API
832
+ */
833
+ info: SchemaInfo;
834
+ /**
835
+ * All API endpoints discovered from the spec
836
+ */
837
+ endpoints: Endpoint[];
838
+ /**
839
+ * All data models (schemas) from the spec
840
+ */
841
+ models: Record<string, DataModel>;
842
+ /**
843
+ * Detected relationships between models
844
+ */
845
+ relationships: Relationship[];
846
+ }
847
+ /**
848
+ * API metadata
849
+ */
850
+ interface SchemaInfo {
851
+ /**
852
+ * API title from the spec
853
+ */
854
+ title: string;
855
+ /**
856
+ * API version
857
+ */
858
+ version: string;
859
+ /**
860
+ * Optional description
861
+ */
862
+ description?: string;
863
+ /**
864
+ * Base URL for the API (if specified)
865
+ */
866
+ baseUrl?: string;
867
+ }
868
+ /**
869
+ * An API endpoint
870
+ */
871
+ interface Endpoint {
872
+ /**
873
+ * HTTP method (GET, POST, PUT, PATCH, DELETE)
874
+ */
875
+ method: HttpMethod;
876
+ /**
877
+ * URL path with parameter placeholders
878
+ * @example "/users/{id}" or "/orders/{orderId}/items"
879
+ */
880
+ path: string;
881
+ /**
882
+ * Operation ID from OpenAPI (if available)
883
+ */
884
+ operationId?: string;
885
+ /**
886
+ * Human-readable summary
887
+ */
888
+ summary?: string;
889
+ /**
890
+ * Detailed description
891
+ */
892
+ description?: string;
893
+ /**
894
+ * Path parameters
895
+ */
896
+ pathParams: ParameterDef[];
897
+ /**
898
+ * Query parameters
899
+ */
900
+ queryParams: ParameterDef[];
901
+ /**
902
+ * Request body schema (for POST/PUT/PATCH)
903
+ */
904
+ requestBody?: RequestBody;
905
+ /**
906
+ * Response schemas by status code
907
+ */
908
+ responses: Record<string, ResponseDef>;
909
+ /**
910
+ * Tags for grouping endpoints
911
+ */
912
+ tags: string[];
913
+ }
914
+ /**
915
+ * HTTP methods supported
916
+ */
917
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
918
+ /**
919
+ * A request or response body definition
920
+ */
921
+ interface RequestBody {
922
+ /**
923
+ * Content type (usually application/json)
924
+ */
925
+ contentType: string;
926
+ /**
927
+ * Reference to the model name, or inline schema
928
+ */
929
+ schema: SchemaRef | DataModel;
930
+ /**
931
+ * Whether the body is required
932
+ */
933
+ required: boolean;
934
+ /**
935
+ * Description of the body
936
+ */
937
+ description?: string;
938
+ }
939
+ /**
940
+ * A response definition
941
+ */
942
+ interface ResponseDef {
943
+ /**
944
+ * HTTP status code
945
+ */
946
+ statusCode: string;
947
+ /**
948
+ * Description of the response
949
+ */
950
+ description?: string;
951
+ /**
952
+ * Content type to schema mapping
953
+ */
954
+ content?: Record<string, SchemaRef | DataModel>;
955
+ }
956
+ /**
957
+ * A parameter definition (path or query)
958
+ */
959
+ interface ParameterDef {
960
+ /**
961
+ * Parameter name
962
+ */
963
+ name: string;
964
+ /**
965
+ * Where the parameter is located
966
+ */
967
+ in: 'path' | 'query' | 'header' | 'cookie';
968
+ /**
969
+ * Whether the parameter is required
970
+ */
971
+ required: boolean;
972
+ /**
973
+ * Parameter type
974
+ */
975
+ type: PropertyType;
976
+ /**
977
+ * Optional format hint
978
+ */
979
+ format?: string;
980
+ /**
981
+ * Description
982
+ */
983
+ description?: string;
984
+ /**
985
+ * Example value
986
+ */
987
+ example?: unknown;
988
+ }
989
+ /**
990
+ * Reference to another schema/model
991
+ */
992
+ interface SchemaRef {
993
+ /**
994
+ * The referenced model name
995
+ */
996
+ $ref: string;
997
+ }
998
+ /**
999
+ * A data model representing an object schema
1000
+ */
1001
+ interface DataModel {
1002
+ /**
1003
+ * Model name (from the schema component name)
1004
+ */
1005
+ name: string;
1006
+ /**
1007
+ * The type of this model
1008
+ */
1009
+ type: ModelType;
1010
+ /**
1011
+ * Description from the spec
1012
+ */
1013
+ description?: string;
1014
+ /**
1015
+ * Properties for object types
1016
+ */
1017
+ properties?: Record<string, PropertyDef>;
1018
+ /**
1019
+ * Required property names
1020
+ */
1021
+ required?: string[];
1022
+ /**
1023
+ * For array types, the item schema
1024
+ */
1025
+ items?: SchemaRef | DataModel;
1026
+ /**
1027
+ * Enum values for enum types
1028
+ */
1029
+ enum?: unknown[];
1030
+ /**
1031
+ * Example value from the spec
1032
+ */
1033
+ example?: unknown;
1034
+ /**
1035
+ * Additional properties schema (for dictionaries)
1036
+ */
1037
+ additionalProperties?: boolean | SchemaRef | DataModel;
1038
+ }
1039
+ /**
1040
+ * Model types
1041
+ */
1042
+ type ModelType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
1043
+ /**
1044
+ * A property definition within a model
1045
+ */
1046
+ interface PropertyDef {
1047
+ /**
1048
+ * Property name
1049
+ */
1050
+ name: string;
1051
+ /**
1052
+ * Property type
1053
+ */
1054
+ type: PropertyType;
1055
+ /**
1056
+ * Format hint (uuid, email, date-time, etc.)
1057
+ */
1058
+ format?: string;
1059
+ /**
1060
+ * Description
1061
+ */
1062
+ description?: string;
1063
+ /**
1064
+ * Whether this property is required
1065
+ */
1066
+ required?: boolean;
1067
+ /**
1068
+ * Whether this property is nullable
1069
+ */
1070
+ nullable?: boolean;
1071
+ /**
1072
+ * Enum values for string enums
1073
+ */
1074
+ enum?: unknown[];
1075
+ /**
1076
+ * For array types, the item schema
1077
+ */
1078
+ items?: SchemaRef | DataModel;
1079
+ /**
1080
+ * Reference to another model (for $ref properties)
1081
+ */
1082
+ $ref?: string;
1083
+ /**
1084
+ * Example value
1085
+ */
1086
+ example?: unknown;
1087
+ /**
1088
+ * Default value
1089
+ */
1090
+ default?: unknown;
1091
+ /**
1092
+ * Minimum value (for numbers)
1093
+ */
1094
+ minimum?: number;
1095
+ /**
1096
+ * Maximum value (for numbers)
1097
+ */
1098
+ maximum?: number;
1099
+ /**
1100
+ * Min length (for strings)
1101
+ */
1102
+ minLength?: number;
1103
+ /**
1104
+ * Max length (for strings)
1105
+ */
1106
+ maxLength?: number;
1107
+ /**
1108
+ * Pattern (regex for strings)
1109
+ */
1110
+ pattern?: string;
1111
+ /**
1112
+ * Detected relationship to another model
1113
+ * Set by relationship detection, not directly from spec
1114
+ */
1115
+ relationshipTo?: RelationshipTarget;
1116
+ /**
1117
+ * Custom extension for explicit relationship hints
1118
+ * @example "x-demokit-relationship": { "model": "User", "field": "id" }
1119
+ */
1120
+ 'x-demokit-relationship'?: RelationshipTarget;
1121
+ }
1122
+ /**
1123
+ * Property types
1124
+ */
1125
+ type PropertyType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
1126
+ /**
1127
+ * A detected relationship between two models
1128
+ */
1129
+ interface Relationship {
1130
+ /**
1131
+ * The source side of the relationship
1132
+ */
1133
+ from: RelationshipSide;
1134
+ /**
1135
+ * The target side of the relationship
1136
+ */
1137
+ to: RelationshipSide;
1138
+ /**
1139
+ * Type of relationship
1140
+ */
1141
+ type: RelationshipType;
1142
+ /**
1143
+ * Whether the relationship is required (not nullable)
1144
+ */
1145
+ required: boolean;
1146
+ /**
1147
+ * How this relationship was detected
1148
+ */
1149
+ detectedBy: RelationshipDetectionMethod;
1150
+ }
1151
+ /**
1152
+ * One side of a relationship
1153
+ */
1154
+ interface RelationshipSide {
1155
+ /**
1156
+ * Model name
1157
+ */
1158
+ model: string;
1159
+ /**
1160
+ * Field name
1161
+ */
1162
+ field: string;
1163
+ }
1164
+ /**
1165
+ * Target for a relationship from a property
1166
+ */
1167
+ interface RelationshipTarget {
1168
+ /**
1169
+ * Target model name
1170
+ */
1171
+ model: string;
1172
+ /**
1173
+ * Target field (usually "id")
1174
+ */
1175
+ field: string;
1176
+ }
1177
+ /**
1178
+ * Types of relationships between models
1179
+ */
1180
+ type RelationshipType = 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many';
1181
+ /**
1182
+ * How a relationship was detected
1183
+ */
1184
+ type RelationshipDetectionMethod = 'explicit-ref' | 'naming-convention' | 'x-demokit-extension' | 'inferred';
1185
+ /**
1186
+ * Helper type to check if something is a schema reference
1187
+ */
1188
+ declare function isSchemaRef(value: unknown): value is SchemaRef;
1189
+ /**
1190
+ * Extract the model name from a $ref string
1191
+ * @example "#/components/schemas/User" -> "User"
1192
+ */
1193
+ declare function extractRefName(ref: string): string;
1194
+
1195
+ /**
1196
+ * OpenAPI 3.x parser for DemoKit
1197
+ *
1198
+ * Parses OpenAPI specs into DemoKit's internal schema representation
1199
+ * with automatic relationship detection.
1200
+ *
1201
+ * Uses @scalar/openapi-parser - a modern, webpack-compatible parser.
1202
+ */
1203
+
1204
+ /**
1205
+ * Options for parsing OpenAPI specs
1206
+ */
1207
+ interface ParseOptions {
1208
+ /**
1209
+ * Whether to dereference all $ref pointers
1210
+ * @default true
1211
+ */
1212
+ dereference?: boolean;
1213
+ /**
1214
+ * Whether to detect relationships automatically
1215
+ * @default true
1216
+ */
1217
+ detectRelationships?: boolean;
1218
+ /**
1219
+ * Whether to include response schemas in models
1220
+ * @default true
1221
+ */
1222
+ includeResponses?: boolean;
1223
+ }
1224
+ /**
1225
+ * Parse an OpenAPI spec from a file path or URL
1226
+ */
1227
+ declare function parseOpenAPIFromPath(pathOrUrl: string, options?: ParseOptions): Promise<DemokitSchema>;
1228
+ /**
1229
+ * Parse an OpenAPI spec from a string (JSON or YAML)
1230
+ */
1231
+ declare function parseOpenAPIFromString(spec: string, options?: ParseOptions): Promise<DemokitSchema>;
1232
+ /**
1233
+ * Parse an OpenAPI spec from an already-parsed object
1234
+ */
1235
+ declare function parseOpenAPIFromObject(spec: Record<string, unknown>, options?: ParseOptions): Promise<DemokitSchema>;
1236
+
1237
+ /**
1238
+ * Types for codebase schema parsers.
1239
+ * These types define the interface for parsing various schema formats
1240
+ * (TypeScript, Zod, Drizzle, Prisma, etc.) into DemokitSchema.
1241
+ */
1242
+
1243
+ /**
1244
+ * Supported schema formats that can be parsed from codebases.
1245
+ */
1246
+ type SchemaFormat = 'typescript' | 'zod' | 'drizzle' | 'prisma' | 'graphql' | 'supabase' | 'trpc' | 'nextjs' | 'openapi' | 'auto';
1247
+ /**
1248
+ * A file to be parsed, with path and content.
1249
+ */
1250
+ interface CodebaseFile {
1251
+ /**
1252
+ * Relative or absolute file path.
1253
+ */
1254
+ path: string;
1255
+ /**
1256
+ * File content as a string.
1257
+ */
1258
+ content: string;
1259
+ }
1260
+ /**
1261
+ * Options for parsing codebase schemas.
1262
+ */
1263
+ interface ParseSchemaOptions {
1264
+ /**
1265
+ * The format to parse as. Use 'auto' to detect.
1266
+ * @default 'auto'
1267
+ */
1268
+ format?: SchemaFormat;
1269
+ /**
1270
+ * Schema/API name for the output.
1271
+ * @default 'Codebase Schema'
1272
+ */
1273
+ name?: string;
1274
+ /**
1275
+ * Schema version.
1276
+ * @default '1.0.0'
1277
+ */
1278
+ version?: string;
1279
+ /**
1280
+ * Whether to detect relationships between models.
1281
+ * @default true
1282
+ */
1283
+ detectRelationships?: boolean;
1284
+ /**
1285
+ * Whether to include inferred relationships from naming conventions.
1286
+ * @default true
1287
+ */
1288
+ inferRelationships?: boolean;
1289
+ }
1290
+ /**
1291
+ * Result of parsing with additional metadata.
1292
+ */
1293
+ interface ParseResult {
1294
+ /**
1295
+ * The parsed schema.
1296
+ */
1297
+ schema: DemokitSchema;
1298
+ /**
1299
+ * The format that was detected/used.
1300
+ */
1301
+ format: SchemaFormat;
1302
+ /**
1303
+ * Any warnings encountered during parsing.
1304
+ */
1305
+ warnings: ParseWarning[];
1306
+ /**
1307
+ * Files that were parsed.
1308
+ */
1309
+ parsedFiles: string[];
1310
+ }
1311
+ /**
1312
+ * A warning encountered during parsing.
1313
+ */
1314
+ interface ParseWarning {
1315
+ /**
1316
+ * Warning code for programmatic handling.
1317
+ */
1318
+ code: string;
1319
+ /**
1320
+ * Human-readable message.
1321
+ */
1322
+ message: string;
1323
+ /**
1324
+ * File where the warning occurred.
1325
+ */
1326
+ file?: string;
1327
+ /**
1328
+ * Line number where the warning occurred.
1329
+ */
1330
+ line?: number;
1331
+ }
1332
+ /**
1333
+ * Detection result for schema format.
1334
+ */
1335
+ interface FormatDetectionResult {
1336
+ /**
1337
+ * The detected format, or null if unknown.
1338
+ */
1339
+ format: SchemaFormat | null;
1340
+ /**
1341
+ * Confidence score from 0-1.
1342
+ */
1343
+ confidence: number;
1344
+ /**
1345
+ * Evidence that led to this detection.
1346
+ */
1347
+ evidence: string[];
1348
+ }
1349
+ /**
1350
+ * Patterns for detecting schema formats from file content.
1351
+ */
1352
+ interface FormatDetectionPatterns {
1353
+ /**
1354
+ * File path patterns (globs).
1355
+ */
1356
+ pathPatterns: string[];
1357
+ /**
1358
+ * Keywords/patterns to search for in content.
1359
+ */
1360
+ contentPatterns: string[];
1361
+ /**
1362
+ * File extensions to match.
1363
+ */
1364
+ extensions: string[];
1365
+ }
1366
+
1367
+ /**
1368
+ * Format detection utilities for codebase schema files.
1369
+ * Detects which schema format (TypeScript, Zod, Drizzle, Prisma, etc.)
1370
+ * a given file or content is written in.
1371
+ */
1372
+
1373
+ /**
1374
+ * Detection patterns for each schema format.
1375
+ */
1376
+ declare const FORMAT_PATTERNS: Record<Exclude<SchemaFormat, 'auto'>, FormatDetectionPatterns>;
1377
+ /**
1378
+ * Priority order when multiple formats are detected.
1379
+ * Formats earlier in the list take precedence.
1380
+ */
1381
+ declare const FORMAT_PRIORITY: SchemaFormat[];
1382
+ /**
1383
+ * Detect the schema format of a single file.
1384
+ */
1385
+ declare function detectFormat(file: CodebaseFile): FormatDetectionResult;
1386
+ /**
1387
+ * Detect the primary schema format from multiple files.
1388
+ * Returns the format with highest total confidence.
1389
+ */
1390
+ declare function detectFormatFromFiles(files: CodebaseFile[]): FormatDetectionResult;
1391
+ /**
1392
+ * Group files by their detected format.
1393
+ */
1394
+ declare function groupFilesByFormat(files: CodebaseFile[]): Map<SchemaFormat, CodebaseFile[]>;
1395
+
1396
+ /**
1397
+ * TypeScript interface/type parser.
1398
+ * Parses TypeScript interface and type declarations into DemokitSchema.
1399
+ *
1400
+ * Supports:
1401
+ * - interface declarations
1402
+ * - type aliases (object types)
1403
+ * - enum declarations
1404
+ * - Generic types (partial support)
1405
+ * - Union/intersection types (partial support)
1406
+ * - Array types
1407
+ * - Optional properties
1408
+ * - JSDoc comments for descriptions
1409
+ */
1410
+
1411
+ /**
1412
+ * Parse TypeScript files containing interface/type definitions.
1413
+ */
1414
+ declare function parseTypeScript(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1415
+
1416
+ /**
1417
+ * Zod schema parser.
1418
+ * Parses Zod validation schemas into DemokitSchema.
1419
+ *
1420
+ * Supports:
1421
+ * - z.object() schemas
1422
+ * - z.string(), z.number(), z.boolean() primitives
1423
+ * - z.array() and z.tuple()
1424
+ * - z.enum() and z.nativeEnum()
1425
+ * - z.optional(), z.nullable()
1426
+ * - z.union(), z.intersection()
1427
+ * - z.lazy() for recursive types
1428
+ * - .describe() for descriptions
1429
+ * - .default() values
1430
+ * - String validations (.email(), .uuid(), .url(), etc.)
1431
+ * - Number validations (.min(), .max(), .int())
1432
+ */
1433
+
1434
+ /**
1435
+ * Parse Zod schema files into DemokitSchema.
1436
+ */
1437
+ declare function parseZod(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1438
+
1439
+ /**
1440
+ * Drizzle ORM schema parser.
1441
+ * Parses Drizzle table definitions and relations into DemokitSchema.
1442
+ *
1443
+ * Supports:
1444
+ * - pgTable(), mysqlTable(), sqliteTable() definitions
1445
+ * - Column types (text, integer, boolean, uuid, timestamp, etc.)
1446
+ * - Primary keys, foreign keys, unique constraints
1447
+ * - relations() function for explicit relationships
1448
+ * - Default values
1449
+ * - Nullable columns
1450
+ *
1451
+ * This parser extracts high-fidelity relationship information
1452
+ * since Drizzle uses explicit relations() declarations.
1453
+ */
1454
+
1455
+ /**
1456
+ * Parse Drizzle schema files into DemokitSchema.
1457
+ */
1458
+ declare function parseDrizzle(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1459
+
1460
+ /**
1461
+ * Prisma schema parser.
1462
+ * Parses Prisma schema files (.prisma) into DemokitSchema.
1463
+ *
1464
+ * Supports:
1465
+ * - model definitions with fields
1466
+ * - Field types (String, Int, Float, Boolean, DateTime, etc.)
1467
+ * - @id, @unique, @default attributes
1468
+ * - @relation for relationships
1469
+ * - Optional fields (?)
1470
+ * - Array fields ([])
1471
+ * - Enums
1472
+ * - @map and @@map for custom names
1473
+ *
1474
+ * Prisma schemas have explicit relationship definitions,
1475
+ * providing high-fidelity relationship detection.
1476
+ */
1477
+
1478
+ /**
1479
+ * Parse Prisma schema files into DemokitSchema.
1480
+ */
1481
+ declare function parsePrisma(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1482
+
1483
+ /**
1484
+ * GraphQL SDL parser.
1485
+ * Parses GraphQL schema files (.graphql, .gql) into DemokitSchema.
1486
+ *
1487
+ * Supports:
1488
+ * - type definitions (type, interface, input, enum)
1489
+ * - Field types (String, Int, Float, Boolean, ID, custom types)
1490
+ * - Non-null (!) and list ([]) modifiers
1491
+ * - Field relationships based on type references
1492
+ * - Query, Mutation, and Subscription types
1493
+ *
1494
+ * GraphQL schemas have explicit type references,
1495
+ * providing high-fidelity relationship detection.
1496
+ */
1497
+
1498
+ /**
1499
+ * Parse GraphQL schema files into DemokitSchema.
1500
+ */
1501
+ declare function parseGraphQL(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1502
+
1503
+ /**
1504
+ * Supabase generated types parser.
1505
+ * Parses Supabase database.types.ts files into DemokitSchema.
1506
+ *
1507
+ * Supports:
1508
+ * - Database interface with Tables property
1509
+ * - Tables.*.Row type for each table
1510
+ * - Column types mapped from PostgreSQL types
1511
+ * - Foreign key relationships from Insert/Update types
1512
+ * - Views and Enums
1513
+ *
1514
+ * Supabase generates types from the database schema,
1515
+ * providing accurate type information and relationships.
1516
+ */
1517
+
1518
+ /**
1519
+ * Parse Supabase types files into DemokitSchema.
1520
+ */
1521
+ declare function parseSupabase(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1522
+
1523
+ /**
1524
+ * tRPC router parser.
1525
+ * Parses tRPC router definitions into DemokitSchema.
1526
+ *
1527
+ * Supports:
1528
+ * - router() definitions with procedure chains
1529
+ * - .input() and .output() Zod schemas
1530
+ * - publicProcedure and protectedProcedure
1531
+ * - Nested routers (appRouter structure)
1532
+ *
1533
+ * tRPC uses Zod for validation, so this parser extracts
1534
+ * Zod schemas and delegates to the Zod parser for details.
1535
+ */
1536
+
1537
+ /**
1538
+ * Parse tRPC router files into DemokitSchema.
1539
+ */
1540
+ declare function parseTRPC(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1541
+
1542
+ /**
1543
+ * Next.js parser.
1544
+ * Parses Next.js API routes and Server Actions into DemokitSchema.
1545
+ *
1546
+ * Supports:
1547
+ * - App Router: app/api/[...]/route.ts (GET, POST, PUT, PATCH, DELETE)
1548
+ * - Pages Router: pages/api/[...].ts (handler function)
1549
+ * - Server Actions: 'use server' directive
1550
+ * - TypeScript types for request/response bodies
1551
+ * - Zod validation schemas in API routes
1552
+ *
1553
+ * Extracts endpoint and schema information from Next.js conventions.
1554
+ */
1555
+
1556
+ /**
1557
+ * Parse Next.js files into DemokitSchema.
1558
+ */
1559
+ declare function parseNextJS(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1560
+
1561
+ /**
1562
+ * Unified schema parser entry point.
1563
+ *
1564
+ * Provides a single `parseSchema()` function that can parse
1565
+ * multiple schema formats and automatically detect the format.
1566
+ *
1567
+ * @example
1568
+ * // Parse with auto-detection
1569
+ * const result = await parseSchema(files)
1570
+ *
1571
+ * // Parse specific format
1572
+ * const result = await parseSchema(files, { format: 'drizzle' })
1573
+ *
1574
+ * // Parse from strings
1575
+ * const result = await parseSchemaFromStrings([
1576
+ * { path: 'schema.ts', content: 'export const users = pgTable(...)' }
1577
+ * ])
1578
+ */
1579
+
1580
+ /**
1581
+ * Parse schema files from a codebase.
1582
+ *
1583
+ * Supports TypeScript, Zod, Drizzle, and Prisma formats.
1584
+ * Can auto-detect the format or use a specified format.
1585
+ *
1586
+ * @param files - Array of files with path and content
1587
+ * @param options - Parsing options
1588
+ * @returns Parsed schema with metadata
1589
+ */
1590
+ declare function parseSchema(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1591
+ /**
1592
+ * Parse multiple formats from a codebase and merge the results.
1593
+ *
1594
+ * This is useful when a codebase uses multiple schema sources
1595
+ * (e.g., Drizzle for database + Zod for validation).
1596
+ *
1597
+ * @param files - Array of files with path and content
1598
+ * @param options - Parsing options
1599
+ * @returns Merged schema from all detected formats
1600
+ */
1601
+ declare function parseSchemaMultiFormat(files: CodebaseFile[], options?: ParseSchemaOptions): ParseResult;
1602
+
1603
+ /**
1604
+ * Relationship detection for DemoKit schemas
1605
+ *
1606
+ * Detects relationships between models using:
1607
+ * 1. Explicit $ref references in OpenAPI
1608
+ * 2. Naming conventions (userId -> User.id)
1609
+ * 3. x-demokit-relationship extension
1610
+ */
1611
+
1612
+ /**
1613
+ * Check if a property looks like a foreign key based on naming conventions
1614
+ */
1615
+ declare function detectRelationshipFromNaming(property: PropertyDef, availableModels: Set<string>): RelationshipTarget | null;
1616
+ /**
1617
+ * Check if a property has an explicit x-demokit-relationship extension
1618
+ */
1619
+ declare function detectRelationshipFromExtension(property: PropertyDef): RelationshipTarget | null;
1620
+ /**
1621
+ * Check if a property is a $ref to another model
1622
+ */
1623
+ declare function detectRelationshipFromRef(property: PropertyDef, availableModels: Set<string>): RelationshipTarget | null;
1624
+ /**
1625
+ * Detect all relationships in a set of models
1626
+ */
1627
+ declare function detectRelationships(models: Record<string, DataModel>): Relationship[];
1628
+ /**
1629
+ * Find all relationships for a specific model
1630
+ */
1631
+ declare function getRelationshipsForModel(modelName: string, relationships: Relationship[]): {
1632
+ outgoing: Relationship[];
1633
+ incoming: Relationship[];
1634
+ };
1635
+ /**
1636
+ * Check if a model is referenced by other models
1637
+ */
1638
+ declare function isModelReferenced(modelName: string, relationships: Relationship[]): boolean;
1639
+ /**
1640
+ * Get the dependency order for models based on relationships
1641
+ * Returns models in order such that dependencies come before dependents
1642
+ */
1643
+ declare function getModelDependencyOrder(models: Record<string, DataModel>, relationships: Relationship[]): string[];
1644
+
1645
+ /**
1646
+ * Schema Merger.
1647
+ * Merges multiple DemokitSchemas from different sources into a unified schema.
1648
+ *
1649
+ * Features:
1650
+ * - Case-insensitive model name matching
1651
+ * - Property merge with source tracking
1652
+ * - Relationship priority (explicit > inferred)
1653
+ * - Conflict detection and resolution
1654
+ * - Endpoint merging from multiple sources
1655
+ */
1656
+
1657
+ /**
1658
+ * Options for schema merging.
1659
+ */
1660
+ interface MergeOptions {
1661
+ /**
1662
+ * How to resolve property conflicts when the same model appears in multiple sources.
1663
+ * - 'prefer-explicit': Prefer properties from more explicit sources (e.g., Drizzle over TypeScript)
1664
+ * - 'prefer-first': Keep the first value encountered
1665
+ * - 'union': Combine all properties, with first taking precedence for conflicts
1666
+ */
1667
+ conflictResolution?: 'prefer-explicit' | 'prefer-first' | 'union';
1668
+ /**
1669
+ * Order of precedence for relationships.
1670
+ * Earlier formats have higher priority.
1671
+ * Default: ['drizzle', 'prisma', 'graphql', 'supabase', 'zod', 'trpc', 'typescript', 'nextjs']
1672
+ */
1673
+ relationshipPriority?: SchemaFormat[];
1674
+ /**
1675
+ * Whether to track the source of each field for debugging.
1676
+ */
1677
+ trackSources?: boolean;
1678
+ /**
1679
+ * Name for the merged schema.
1680
+ */
1681
+ name?: string;
1682
+ /**
1683
+ * Version for the merged schema.
1684
+ */
1685
+ version?: string;
1686
+ }
1687
+ /**
1688
+ * A source schema with its format identifier.
1689
+ */
1690
+ interface SchemaSource {
1691
+ format: SchemaFormat;
1692
+ schema: DemokitSchema;
1693
+ }
1694
+ /**
1695
+ * Result of a merge operation.
1696
+ */
1697
+ interface MergeResult {
1698
+ /**
1699
+ * The merged schema.
1700
+ */
1701
+ schema: DemokitSchema;
1702
+ /**
1703
+ * Conflicts detected during merge.
1704
+ */
1705
+ conflicts: MergeConflict[];
1706
+ /**
1707
+ * Source tracking for each model (if enabled).
1708
+ */
1709
+ sources?: ModelSourceMap;
1710
+ /**
1711
+ * Formats that were merged.
1712
+ */
1713
+ mergedFormats: SchemaFormat[];
1714
+ }
1715
+ /**
1716
+ * Describes a merge conflict.
1717
+ */
1718
+ interface MergeConflict {
1719
+ type: 'model' | 'property' | 'relationship';
1720
+ modelName: string;
1721
+ propertyName?: string;
1722
+ sources: SchemaFormat[];
1723
+ resolution: 'kept-first' | 'merged' | 'overwritten';
1724
+ details?: string;
1725
+ }
1726
+ /**
1727
+ * Tracks which source provided each model/property.
1728
+ */
1729
+ interface ModelSourceMap {
1730
+ [modelName: string]: {
1731
+ primarySource: SchemaFormat;
1732
+ properties: {
1733
+ [propertyName: string]: SchemaFormat;
1734
+ };
1735
+ };
1736
+ }
1737
+ /**
1738
+ * Merge multiple schemas into a unified schema.
1739
+ *
1740
+ * @param sources - Array of schemas with their format identifiers
1741
+ * @param options - Merge options
1742
+ * @returns Merged schema with conflict information
1743
+ */
1744
+ declare function mergeSchemas(sources: SchemaSource[], options?: MergeOptions): MergeResult;
1745
+ /**
1746
+ * Compare two schemas and return the differences.
1747
+ */
1748
+ declare function diffSchemas(base: DemokitSchema, updated: DemokitSchema): SchemaDiff;
1749
+ /**
1750
+ * Schema diff result.
1751
+ */
1752
+ interface SchemaDiff {
1753
+ added: SchemaDiffItem[];
1754
+ removed: SchemaDiffItem[];
1755
+ modified: SchemaDiffItem[];
1756
+ }
1757
+ /**
1758
+ * A single diff item.
1759
+ */
1760
+ interface SchemaDiffItem {
1761
+ type: 'model' | 'relationship' | 'endpoint';
1762
+ name: string;
1763
+ details: unknown;
1764
+ }
1765
+ /**
1766
+ * Property diff.
1767
+ */
1768
+ interface PropertyDiff {
1769
+ name: string;
1770
+ change: 'added' | 'removed' | 'modified';
1771
+ oldValue?: PropertyDef;
1772
+ newValue?: PropertyDef;
1773
+ }
1774
+
1775
+ /**
1776
+ * Error handling utilities for schema parsing.
1777
+ *
1778
+ * Provides custom error types and safe parsing utilities
1779
+ * for graceful error recovery during schema parsing.
1780
+ */
1781
+
1782
+ /**
1783
+ * Base error class for schema parsing errors.
1784
+ */
1785
+ declare class SchemaParseError extends Error {
1786
+ readonly code: string;
1787
+ readonly filePath?: string | undefined;
1788
+ readonly line?: number | undefined;
1789
+ constructor(message: string, code: string, filePath?: string | undefined, line?: number | undefined);
1790
+ }
1791
+ /**
1792
+ * Error thrown when a format cannot be detected.
1793
+ */
1794
+ declare class FormatDetectionError extends SchemaParseError {
1795
+ constructor(message: string, filePath?: string);
1796
+ }
1797
+ /**
1798
+ * Error thrown when a file cannot be parsed.
1799
+ */
1800
+ declare class FileParseError extends SchemaParseError {
1801
+ constructor(message: string, filePath: string, line?: number);
1802
+ }
1803
+ /**
1804
+ * Error thrown when schema validation fails.
1805
+ */
1806
+ declare class SchemaValidationError extends SchemaParseError {
1807
+ readonly validationErrors: string[];
1808
+ constructor(message: string, validationErrors: string[]);
1809
+ }
1810
+ /**
1811
+ * Error thrown when merging schemas fails.
1812
+ */
1813
+ declare class SchemaMergeError extends SchemaParseError {
1814
+ readonly modelName?: string | undefined;
1815
+ constructor(message: string, modelName?: string | undefined);
1816
+ }
1817
+ /**
1818
+ * Result of a safe operation that may fail.
1819
+ */
1820
+ type SafeResult<T> = {
1821
+ success: true;
1822
+ value: T;
1823
+ warnings: ParseWarning[];
1824
+ } | {
1825
+ success: false;
1826
+ error: Error;
1827
+ warnings: ParseWarning[];
1828
+ };
1829
+ /**
1830
+ * Safely execute a parsing function and capture errors as warnings.
1831
+ *
1832
+ * @param fn - The function to execute
1833
+ * @param fallback - Fallback value if the function fails
1834
+ * @param errorCode - Warning code to use if the function fails
1835
+ * @returns Result with value or error
1836
+ */
1837
+ declare function safeExecute<T>(fn: () => T, fallback: T, errorCode: string): {
1838
+ value: T;
1839
+ warning?: ParseWarning;
1840
+ };
1841
+ /**
1842
+ * Safely parse content with error recovery.
1843
+ * Returns partial results with warnings instead of failing completely.
1844
+ *
1845
+ * @param items - Array of items to process
1846
+ * @param processor - Function to process each item
1847
+ * @param errorCode - Warning code prefix for errors
1848
+ * @returns Processed results and accumulated warnings
1849
+ */
1850
+ declare function safeProcessMany<T, R>(items: T[], processor: (item: T) => R, errorCode: string): {
1851
+ results: R[];
1852
+ warnings: ParseWarning[];
1853
+ };
1854
+ /**
1855
+ * Create a warning from an error.
1856
+ */
1857
+ declare function errorToWarning(error: unknown, code: string, file?: string): ParseWarning;
1858
+ /**
1859
+ * Aggregate multiple warnings into a summary warning.
1860
+ */
1861
+ declare function aggregateWarnings(warnings: ParseWarning[], summaryCode: string, summaryPrefix: string): ParseWarning[];
1862
+ /**
1863
+ * Check if an error is recoverable (should result in warning, not failure).
1864
+ */
1865
+ declare function isRecoverableError(error: unknown): boolean;
1866
+
1867
+ /**
1868
+ * Types for @demokit-ai/codegen
1869
+ *
1870
+ * Includes validation types, generation options, and output formats.
1871
+ */
1872
+
1873
+ /**
1874
+ * Result of validating demo data against a schema
1875
+ */
1876
+ interface ValidationResult {
1877
+ /** Whether all validations passed */
1878
+ valid: boolean;
1879
+ /** Critical errors that must be fixed */
1880
+ errors: ValidationError[];
1881
+ /** Non-critical issues that should be reviewed */
1882
+ warnings: ValidationWarning[];
1883
+ /** Summary statistics */
1884
+ stats: ValidationStats;
1885
+ }
1886
+ /**
1887
+ * A validation error - data that violates schema constraints
1888
+ */
1889
+ interface ValidationError {
1890
+ /** Type of validation failure */
1891
+ type: ValidationErrorType;
1892
+ /** Model where the error occurred */
1893
+ model: string;
1894
+ /** Field where the error occurred */
1895
+ field: string;
1896
+ /** Human-readable error message */
1897
+ message: string;
1898
+ /** The invalid value (for debugging) */
1899
+ value?: unknown;
1900
+ /** Expected value or constraint */
1901
+ expected?: string;
1902
+ /** Record ID if applicable */
1903
+ recordId?: string;
1904
+ }
1905
+ /**
1906
+ * Types of validation errors
1907
+ */
1908
+ type ValidationErrorType = 'missing_reference' | 'type_mismatch' | 'format_invalid' | 'constraint_violation' | 'required_missing' | 'enum_invalid' | 'timestamp_order' | 'array_empty' | 'duplicate_id';
1909
+ /**
1910
+ * A validation warning - issues that may be intentional
1911
+ */
1912
+ interface ValidationWarning {
1913
+ /** Type of warning */
1914
+ type: ValidationWarningType;
1915
+ /** Model where the warning occurred */
1916
+ model: string;
1917
+ /** Field where the warning occurred */
1918
+ field: string;
1919
+ /** Human-readable warning message */
1920
+ message: string;
1921
+ /** The suspicious value */
1922
+ value?: unknown;
1923
+ }
1924
+ /**
1925
+ * Types of validation warnings
1926
+ */
1927
+ type ValidationWarningType = 'orphaned_record' | 'suspicious_value' | 'missing_optional' | 'empty_string';
1928
+ /**
1929
+ * Statistics about the validation run
1930
+ */
1931
+ interface ValidationStats {
1932
+ /** Total number of records validated */
1933
+ totalRecords: number;
1934
+ /** Records per model */
1935
+ recordsByModel: Record<string, number>;
1936
+ /** Number of relationships validated */
1937
+ relationshipsChecked: number;
1938
+ /** Number of type checks performed */
1939
+ typeChecks: number;
1940
+ /** Duration of validation in ms */
1941
+ durationMs: number;
1942
+ }
1943
+ /**
1944
+ * A validation rule that can be applied to data
1945
+ */
1946
+ interface ValidationRule {
1947
+ /** Unique identifier for this rule */
1948
+ id: string;
1949
+ /** Model this rule applies to */
1950
+ model: string;
1951
+ /** Field this rule applies to */
1952
+ field: string;
1953
+ /** Type of check to perform */
1954
+ check: ValidationCheck;
1955
+ /** Target field or value for comparison checks */
1956
+ target?: string;
1957
+ /** Whether this is a required field */
1958
+ required?: boolean;
1959
+ /** Custom error message */
1960
+ message?: string;
1961
+ }
1962
+ /**
1963
+ * Types of validation checks
1964
+ */
1965
+ type ValidationCheck = 'isString' | 'isNumber' | 'isInteger' | 'isBoolean' | 'isArray' | 'isObject' | 'isNull' | 'isUUID' | 'isEmail' | 'isURL' | 'isISO8601' | 'isDate' | 'isDateTime' | 'minLength' | 'maxLength' | 'minimum' | 'maximum' | 'pattern' | 'existsIn' | 'isUnique' | 'equals' | 'beforeOrEqual' | 'afterOrEqual' | 'arrayNotEmpty' | 'arrayMinLength' | 'arrayMaxLength' | 'inEnum';
1966
+ /**
1967
+ * Configuration for the rule generator
1968
+ */
1969
+ interface RuleGeneratorConfig {
1970
+ /** Whether to generate rules for optional fields */
1971
+ includeOptional?: boolean;
1972
+ /** Whether to generate relationship rules */
1973
+ includeRelationships?: boolean;
1974
+ /** Whether to generate format validation rules */
1975
+ includeFormats?: boolean;
1976
+ /** Custom rules to add */
1977
+ customRules?: ValidationRule[];
1978
+ }
1979
+ /**
1980
+ * Demo data for a single model
1981
+ */
1982
+ type ModelData = Record<string, unknown>[];
1983
+ /**
1984
+ * Complete demo data set
1985
+ */
1986
+ type DemoData = Record<string, ModelData>;
1987
+ /**
1988
+ * Options for the validator
1989
+ */
1990
+ interface ValidatorOptions {
1991
+ /** Schema to validate against */
1992
+ schema: DemokitSchema;
1993
+ /** Whether to collect warnings (slower) */
1994
+ collectWarnings?: boolean;
1995
+ /** Whether to stop on first error */
1996
+ failFast?: boolean;
1997
+ /** Maximum errors to collect before stopping */
1998
+ maxErrors?: number;
1999
+ /** Custom validation rules to add */
2000
+ customRules?: ValidationRule[];
2001
+ }
2002
+ /**
2003
+ * Level of data generation
2004
+ */
2005
+ type GenerationLevel = 'schema-valid' | 'relationship-valid' | 'narrative-driven';
2006
+ /**
2007
+ * Options for data generation
2008
+ */
2009
+ interface GenerationOptions {
2010
+ /** Level of generation */
2011
+ level: GenerationLevel;
2012
+ /** Number of records per model */
2013
+ counts?: Record<string, number>;
2014
+ /** Base timestamp for reproducible data */
2015
+ baseTimestamp?: number;
2016
+ /** Seed for random generation - different seed produces different data */
2017
+ seed?: number;
2018
+ /** Output format */
2019
+ format?: 'typescript' | 'json';
2020
+ /** Whether to include validation */
2021
+ validate?: boolean;
2022
+ /** Custom generation rules from project settings */
2023
+ customRules?: GenerationRulesConfig;
2024
+ }
2025
+ /**
2026
+ * Configuration for custom field generation rules
2027
+ * Stored in projects.settings.generationRules
2028
+ */
2029
+ interface GenerationRulesConfig {
2030
+ /** Schema version for migration support */
2031
+ version: 1;
2032
+ /** Per-field rules, keyed by "ModelName.fieldName" */
2033
+ fieldRules: Record<string, FieldRule>;
2034
+ /** Uploaded datasets for correlated value generation, keyed by dataset ID */
2035
+ datasets?: Record<string, Dataset>;
2036
+ }
2037
+ /**
2038
+ * A rule for generating values for a specific field
2039
+ */
2040
+ type FieldRule = StringFieldRule | NumberFieldRule | IntegerFieldRule | BooleanFieldRule | EnumFieldRule | DatasetFieldRule;
2041
+ /**
2042
+ * Rule for generating string field values
2043
+ */
2044
+ interface StringFieldRule {
2045
+ type: 'string';
2046
+ strategy: 'oneOf' | 'pattern';
2047
+ /** For 'oneOf' strategy - pick randomly from this list */
2048
+ values?: string[];
2049
+ /** For 'pattern' strategy - template like "SKU-{0000}" where {0000} is replaced with zero-padded number */
2050
+ pattern?: string;
2051
+ }
2052
+ /**
2053
+ * Rule for generating number field values
2054
+ */
2055
+ interface NumberFieldRule {
2056
+ type: 'number';
2057
+ strategy: 'range' | 'fixed';
2058
+ /** For 'range' strategy */
2059
+ min?: number;
2060
+ max?: number;
2061
+ /** Number of decimal places (default: 2) */
2062
+ precision?: number;
2063
+ /** For 'fixed' strategy - always use this value */
2064
+ value?: number;
2065
+ }
2066
+ /**
2067
+ * Rule for generating integer field values
2068
+ */
2069
+ interface IntegerFieldRule {
2070
+ type: 'integer';
2071
+ strategy: 'range' | 'fixed';
2072
+ min?: number;
2073
+ max?: number;
2074
+ value?: number;
2075
+ }
2076
+ /**
2077
+ * Rule for generating boolean field values
2078
+ */
2079
+ interface BooleanFieldRule {
2080
+ type: 'boolean';
2081
+ strategy: 'fixed' | 'weighted';
2082
+ /** For 'fixed' strategy - always this value */
2083
+ value?: boolean;
2084
+ /** For 'weighted' strategy - probability of true (0-1) */
2085
+ trueProbability?: number;
2086
+ }
2087
+ /**
2088
+ * Rule for generating enum field values
2089
+ */
2090
+ interface EnumFieldRule {
2091
+ type: 'enum';
2092
+ strategy: 'subset' | 'weighted';
2093
+ /** For 'subset' strategy - only use these values */
2094
+ allowedValues?: string[];
2095
+ /** For 'weighted' strategy - value -> weight mapping */
2096
+ weights?: Record<string, number>;
2097
+ }
2098
+ /**
2099
+ * Rule for generating values from a linked dataset column
2100
+ * Enables row-based correlation - multiple fields linked to the same dataset
2101
+ * will use values from the same row within a record
2102
+ */
2103
+ interface DatasetFieldRule {
2104
+ type: 'fromDataset';
2105
+ /** ID of the dataset to pull values from */
2106
+ datasetId: string;
2107
+ /** Column name to use for this field's values */
2108
+ column: string;
2109
+ }
2110
+ /**
2111
+ * A dataset containing rows of correlated values
2112
+ * Limited to ~1000 rows for in-memory storage in project settings
2113
+ */
2114
+ interface Dataset {
2115
+ /** Unique identifier for the dataset */
2116
+ id: string;
2117
+ /** Human-readable name for display */
2118
+ name: string;
2119
+ /** Column headers from CSV */
2120
+ columns: string[];
2121
+ /** Row data - array of arrays matching column order */
2122
+ rows: string[][];
2123
+ /** When the dataset was created/uploaded */
2124
+ createdAt: string;
2125
+ /** Optional description of the dataset contents */
2126
+ description?: string;
2127
+ }
2128
+ /**
2129
+ * Result of parsing CSV content
2130
+ */
2131
+ interface ParseCSVResult {
2132
+ /** Whether parsing succeeded */
2133
+ success: boolean;
2134
+ /** Column headers (if successful) */
2135
+ columns?: string[];
2136
+ /** Row data (if successful) */
2137
+ rows?: string[][];
2138
+ /** Error message (if failed) */
2139
+ error?: string;
2140
+ /** Whether rows were truncated to meet limit */
2141
+ truncated?: boolean;
2142
+ /** Original row count before truncation */
2143
+ originalRowCount?: number;
2144
+ }
2145
+ /**
2146
+ * Result of data generation
2147
+ */
2148
+ interface GenerationResult {
2149
+ /** The generated data */
2150
+ data: DemoData;
2151
+ /** Generated fixture code (if format is typescript) */
2152
+ fixtures?: string;
2153
+ /** Validation results */
2154
+ validation: ValidationResult;
2155
+ /** Generation metadata */
2156
+ metadata: GenerationMetadata;
2157
+ }
2158
+ /**
2159
+ * Metadata about the generation process
2160
+ */
2161
+ interface GenerationMetadata {
2162
+ /** Generation level used */
2163
+ level: GenerationLevel;
2164
+ /** Timestamp when generated */
2165
+ generatedAt: string;
2166
+ /** Total records generated */
2167
+ totalRecords: number;
2168
+ /** Records per model */
2169
+ recordsByModel: Record<string, number>;
2170
+ /** IDs used in generation */
2171
+ usedIds: Record<string, string[]>;
2172
+ /** Duration of generation in ms */
2173
+ durationMs: number;
2174
+ }
2175
+ /**
2176
+ * Context about the application being demoed
2177
+ */
2178
+ interface AppContext {
2179
+ /** Application name */
2180
+ name: string;
2181
+ /** What the app does */
2182
+ description: string;
2183
+ /** Domain (e-commerce, b2b-saas, etc.) */
2184
+ domain: string;
2185
+ /** Key entities and their purposes */
2186
+ keyEntities: EntityContext[];
2187
+ /** Main features/capabilities */
2188
+ features: string[];
2189
+ }
2190
+ /**
2191
+ * Context about a specific entity
2192
+ */
2193
+ interface EntityContext {
2194
+ /** Entity/model name */
2195
+ name: string;
2196
+ /** What this entity represents */
2197
+ purpose: string;
2198
+ /** Key fields to focus on */
2199
+ keyFields: string[];
2200
+ /** Business rules that apply */
2201
+ businessRules?: string[];
2202
+ }
2203
+ /**
2204
+ * Narrative for generating story-driven data
2205
+ */
2206
+ interface DemoNarrative {
2207
+ /** Overall scenario */
2208
+ scenario: string;
2209
+ /** Key story points to hit */
2210
+ keyPoints: string[];
2211
+ /** Named characters/personas */
2212
+ characters?: Character[];
2213
+ /** Timeline of events */
2214
+ timeline?: TimelineEvent[];
2215
+ /** Metric targets */
2216
+ metrics?: MetricTarget[];
2217
+ }
2218
+ /**
2219
+ * A character/persona in the demo
2220
+ */
2221
+ interface Character {
2222
+ /** Character name */
2223
+ name: string;
2224
+ /** Role (customer, admin, etc.) */
2225
+ role: string;
2226
+ /** Character description */
2227
+ description?: string;
2228
+ }
2229
+ /**
2230
+ * A timeline event in the narrative
2231
+ */
2232
+ interface TimelineEvent {
2233
+ /** When this happens (relative or absolute) */
2234
+ when: string;
2235
+ /** What happens */
2236
+ event: string;
2237
+ /** Which characters are involved */
2238
+ characters?: string[];
2239
+ }
2240
+ /**
2241
+ * A metric target for the narrative
2242
+ */
2243
+ interface MetricTarget {
2244
+ /** Metric name */
2245
+ name: string;
2246
+ /** Target value or description */
2247
+ value?: string;
2248
+ /** Trend (increasing, declining, stable) */
2249
+ trend?: 'increasing' | 'declining' | 'stable';
2250
+ /** Percentage change */
2251
+ amount?: string;
2252
+ }
2253
+
2254
+ /**
2255
+ * Main generator orchestrator for demo data generation
2256
+ *
2257
+ * Supports two levels:
2258
+ * - Level 1 (schema-valid): Generate data that matches types
2259
+ * - Level 2 (relationship-valid): Generate data with valid references
2260
+ */
2261
+
2262
+ /**
2263
+ * Generate demo data from a schema
2264
+ */
2265
+ declare function generateDemoData(schema: DemokitSchema, options?: GenerationOptions): GenerationResult;
2266
+
2267
+ /**
2268
+ * ID generation utilities for demo data
2269
+ *
2270
+ * Generates consistent, deterministic IDs for reproducible fixtures.
2271
+ */
2272
+ /**
2273
+ * Generate a UUID v4 (random)
2274
+ * Uses a simple implementation for portability
2275
+ */
2276
+ declare function generateUUID(): string;
2277
+ /**
2278
+ * Generate a deterministic UUID from a seed
2279
+ * Useful for reproducible fixtures
2280
+ */
2281
+ declare function generateSeededUUID(seed: number): string;
2282
+ /**
2283
+ * Generate a model-specific ID
2284
+ * Format: {prefix}_{index} or UUID based on format hint
2285
+ */
2286
+ declare function generateIdForModel(modelName: string, index: number, format?: string): string;
2287
+ /**
2288
+ * Generate an ID based on a property definition
2289
+ */
2290
+ declare function generateId(format?: string, index?: number): string;
2291
+ /**
2292
+ * Generate a prefixed ID
2293
+ * @example generatePrefixedId('user', 1) => 'user_001'
2294
+ */
2295
+ declare function generatePrefixedId(prefix: string, index: number): string;
2296
+ /**
2297
+ * Generate a CUID-like ID
2298
+ * Format: c + timestamp + random
2299
+ */
2300
+ declare function generateCuid(): string;
2301
+ /**
2302
+ * Generate a ULID-like ID
2303
+ * Format: timestamp (10 chars) + random (16 chars)
2304
+ */
2305
+ declare function generateUlid(): string;
2306
+
2307
+ interface GeneratedAddress {
2308
+ line1: string;
2309
+ line2?: string;
2310
+ city: string;
2311
+ state: string;
2312
+ stateFull: string;
2313
+ country: string;
2314
+ countryCode: string;
2315
+ postalCode: string;
2316
+ formatted: string;
2317
+ }
2318
+
2319
+ /**
2320
+ * Value generators for different property types
2321
+ *
2322
+ * Generates realistic demo data based on property type, format, and constraints.
2323
+ */
2324
+
2325
+ /**
2326
+ * Context for generating correlated values within a single record.
2327
+ * This allows related fields (like city, state, zip) to be consistent,
2328
+ * and ensures fields linked to the same dataset use the same row.
2329
+ */
2330
+ interface RecordContext {
2331
+ /** Pre-generated correlated address for this record */
2332
+ address?: GeneratedAddress;
2333
+ /** Country code preference (US, CA, GB, AU, DE) */
2334
+ countryCode?: string;
2335
+ /**
2336
+ * Pre-selected row indices for each dataset (Phase 2).
2337
+ * Key is dataset ID, value is the row index to use.
2338
+ * This ensures multiple fields linked to the same dataset use the same row.
2339
+ */
2340
+ datasetRowIndices?: Map<string, number>;
2341
+ }
2342
+ /**
2343
+ * Generate a value for a property definition
2344
+ *
2345
+ * @param propDef - The property definition from the schema
2346
+ * @param index - The record index (0-based)
2347
+ * @param baseTimestamp - Optional base timestamp for date generation
2348
+ * @param seed - Random seed for deterministic generation
2349
+ * @param recordContext - Optional context for correlated field generation
2350
+ * @param customRule - Optional custom generation rule for this field
2351
+ * @param datasets - Optional datasets for fromDataset rules (Phase 2)
2352
+ */
2353
+ declare function generateValue(propDef: PropertyDef, index: number, baseTimestamp?: number, seed?: number, recordContext?: RecordContext, customRule?: FieldRule, datasets?: Record<string, Dataset>): unknown;
2354
+
2355
+ /**
2356
+ * CSV Parser for Linked Datasets
2357
+ *
2358
+ * Parses CSV content into structured data for use in generation rules.
2359
+ * Supports:
2360
+ * - Quoted fields with commas and newlines
2361
+ * - Header row detection
2362
+ * - Row limit enforcement (1000 rows max)
2363
+ * - Validation of consistent column counts
2364
+ */
2365
+
2366
+ /**
2367
+ * Parse CSV content into columns and rows
2368
+ *
2369
+ * @param content - Raw CSV content as a string
2370
+ * @returns ParseCSVResult with columns, rows, or error
2371
+ */
2372
+ declare function parseCSV(content: string): ParseCSVResult;
2373
+ /**
2374
+ * Generate a unique dataset ID
2375
+ */
2376
+ declare function generateDatasetId(): string;
2377
+ /**
2378
+ * Validate that a dataset name is valid
2379
+ */
2380
+ declare function validateDatasetName(name: string): string | null;
2381
+
2382
+ /**
2383
+ * App Context Inference
2384
+ *
2385
+ * Analyzes a DemokitSchema to infer what the application does,
2386
+ * its domain, key entities, and features. This provides context
2387
+ * for narrative-driven data generation.
2388
+ *
2389
+ * The inference process works in several stages:
2390
+ * 1. Domain detection - What type of application is this?
2391
+ * 2. Entity analysis - What are the key data objects?
2392
+ * 3. Feature inference - What can users do with the app?
2393
+ * 4. Business rule extraction - What constraints apply?
2394
+ *
2395
+ * @example
2396
+ * ```typescript
2397
+ * const schema = await importFromOpenAPI('api.yaml')
2398
+ * const context = inferAppContext(schema)
2399
+ * // context.domain === 'e-commerce'
2400
+ * // context.keyEntities includes Product, Order, Customer
2401
+ * ```
2402
+ */
2403
+
2404
+ /**
2405
+ * Infer application context from a schema.
2406
+ *
2407
+ * This is the main entry point for context inference. It analyzes the schema
2408
+ * structure to understand what the application does and how its data relates.
2409
+ *
2410
+ * @param schema - The parsed DemokitSchema from an OpenAPI spec
2411
+ * @returns AppContext with inferred domain, entities, and features
2412
+ *
2413
+ * @example
2414
+ * ```typescript
2415
+ * const context = inferAppContext(schema)
2416
+ * console.log(context.domain) // 'e-commerce'
2417
+ * console.log(context.keyEntities.length) // 5
2418
+ * ```
2419
+ */
2420
+ declare function inferAppContext(schema: DemokitSchema): AppContext;
2421
+ /**
2422
+ * Create a custom app context with explicit values.
2423
+ *
2424
+ * Use this when the user wants to provide their own context rather than
2425
+ * relying on inference. Useful for demos where the inferred context
2426
+ * doesn't match the intended story.
2427
+ *
2428
+ * @param name - Application name
2429
+ * @param description - What the app does
2430
+ * @param domain - Application domain
2431
+ * @param entities - Key entities with their purposes
2432
+ * @param features - Main features/capabilities
2433
+ * @returns Complete AppContext object
2434
+ *
2435
+ * @example
2436
+ * ```typescript
2437
+ * const context = createAppContext(
2438
+ * 'ShopFlow',
2439
+ * 'Enterprise e-commerce platform',
2440
+ * 'e-commerce',
2441
+ * [{ name: 'Product', purpose: 'Items for sale', keyFields: ['id', 'price'] }],
2442
+ * ['Checkout', 'Inventory Management']
2443
+ * )
2444
+ * ```
2445
+ */
2446
+ declare function createAppContext(name: string, description: string, domain: string, entities: EntityContext[], features: string[]): AppContext;
2447
+ /**
2448
+ * Merge inferred context with user-provided overrides.
2449
+ *
2450
+ * Allows users to customize specific parts of the inferred context
2451
+ * while keeping the rest. Useful for fine-tuning without starting
2452
+ * from scratch.
2453
+ *
2454
+ * @param inferred - The automatically inferred context
2455
+ * @param overrides - User-provided values to override
2456
+ * @returns Merged context with overrides taking precedence
2457
+ *
2458
+ * @example
2459
+ * ```typescript
2460
+ * const inferred = inferAppContext(schema)
2461
+ * const custom = mergeAppContext(inferred, {
2462
+ * name: 'My Custom App Name',
2463
+ * domain: 'b2b-saas', // Override the detected domain
2464
+ * })
2465
+ * ```
2466
+ */
2467
+ declare function mergeAppContext(inferred: AppContext, overrides: Partial<AppContext>): AppContext;
2468
+
2469
+ /**
2470
+ * Output Formatters
2471
+ *
2472
+ * Convert generated demo data into various output formats for different use cases:
2473
+ *
2474
+ * - **TypeScript**: Type-safe fixture files with const assertions
2475
+ * - **JSON**: Standard data interchange format with optional metadata
2476
+ * - **SQL**: INSERT statements for database seeding
2477
+ * - **CSV**: Spreadsheet-compatible format for individual models
2478
+ *
2479
+ * Each formatter handles:
2480
+ * - Proper escaping for the target format
2481
+ * - Optional headers/metadata
2482
+ * - Null and special value handling
2483
+ * - Nested objects and arrays
2484
+ *
2485
+ * @example
2486
+ * ```typescript
2487
+ * // Generate TypeScript fixtures
2488
+ * const tsCode = formatAsTypeScript(data, { asConst: true })
2489
+ *
2490
+ * // Generate JSON with metadata
2491
+ * const json = formatAsJSON(data, { includeMetadata: true })
2492
+ *
2493
+ * // Generate SQL INSERT statements
2494
+ * const sql = formatAsSQL(data, { tableName: name => `tbl_${name}` })
2495
+ *
2496
+ * // Generate CSV for a specific model
2497
+ * const csv = formatAsCSV(data, 'Customer')
2498
+ * ```
2499
+ *
2500
+ * @module
2501
+ */
2502
+
2503
+ /**
2504
+ * Output format options for TypeScript generation
2505
+ *
2506
+ * Controls the generated TypeScript code structure and styling.
2507
+ *
2508
+ * @example
2509
+ * ```typescript
2510
+ * const options: OutputOptions = {
2511
+ * asConst: true, // Add 'as const' for type safety
2512
+ * indent: 2, // 2-space indentation
2513
+ * includeHeader: true, // Add generation comment
2514
+ * narrative: myNarrative, // Include narrative in header
2515
+ * }
2516
+ * ```
2517
+ */
2518
+ interface OutputOptions {
2519
+ /** Whether to include TypeScript 'as const' assertions. Defaults to true. */
2520
+ asConst?: boolean;
2521
+ /** Whether to include type annotations (future use). */
2522
+ includeTypes?: boolean;
2523
+ /** Indentation in spaces. Defaults to 2. */
2524
+ indent?: number;
2525
+ /** Whether to add a comment header with generation info. Defaults to true. */
2526
+ includeHeader?: boolean;
2527
+ /** Narrative for header comments (scenario, key points). */
2528
+ narrative?: DemoNarrative;
2529
+ }
2530
+ /**
2531
+ * Format demo data as TypeScript code
2532
+ *
2533
+ * Generates a TypeScript module with:
2534
+ * - Header comment with generation timestamp
2535
+ * - Optional narrative info (scenario, key points)
2536
+ * - Individual exports per model (DEMO_USER, DEMO_ORDER, etc.)
2537
+ * - Combined DEMO_DATA export with all models
2538
+ * - 'as const' assertions for full type inference
2539
+ *
2540
+ * Model names are converted to CONSTANT_CASE for variable names.
2541
+ *
2542
+ * @param data - Demo data object (model names → record arrays)
2543
+ * @param options - Formatting options (asConst, indent, header, narrative)
2544
+ * @returns TypeScript source code as string
2545
+ *
2546
+ * @example
2547
+ * ```typescript
2548
+ * const data = {
2549
+ * User: [{ id: '1', name: 'Alice' }],
2550
+ * Order: [{ id: '1', userId: '1', total: 100 }],
2551
+ * }
2552
+ *
2553
+ * const code = formatAsTypeScript(data, {
2554
+ * asConst: true,
2555
+ * narrative: { scenario: 'Demo', keyPoints: ['Show users'] },
2556
+ * })
2557
+ *
2558
+ * // Output:
2559
+ * // /**
2560
+ * // * Auto-generated demo fixtures
2561
+ * // * Scenario: Demo
2562
+ * // * Key points:
2563
+ * // * - Show users
2564
+ * // *‍/
2565
+ * // export const DEMO_USER = [...] as const
2566
+ * // export const DEMO_ORDER = [...] as const
2567
+ * // export const DEMO_DATA = { User: DEMO_USER, Order: DEMO_ORDER } as const
2568
+ * ```
2569
+ */
2570
+ declare function formatAsTypeScript(data: DemoData, options?: OutputOptions): string;
2571
+ /**
2572
+ * Format demo data as JSON
2573
+ *
2574
+ * Generates standard JSON output with optional metadata wrapper.
2575
+ *
2576
+ * Without metadata:
2577
+ * ```json
2578
+ * { "User": [...], "Order": [...] }
2579
+ * ```
2580
+ *
2581
+ * With metadata:
2582
+ * ```json
2583
+ * {
2584
+ * "_metadata": { "generatedAt": "...", "modelCount": 2, "recordCount": 10 },
2585
+ * "data": { "User": [...], "Order": [...] }
2586
+ * }
2587
+ * ```
2588
+ *
2589
+ * @param data - Demo data object (model names → record arrays)
2590
+ * @param options - Formatting options (indent, includeMetadata)
2591
+ * @returns JSON string
2592
+ *
2593
+ * @example
2594
+ * ```typescript
2595
+ * // Simple JSON output
2596
+ * const json = formatAsJSON(data)
2597
+ *
2598
+ * // JSON with metadata
2599
+ * const jsonWithMeta = formatAsJSON(data, { includeMetadata: true })
2600
+ * ```
2601
+ */
2602
+ declare function formatAsJSON(data: DemoData, options?: {
2603
+ indent?: number;
2604
+ includeMetadata?: boolean;
2605
+ }): string;
2606
+ /**
2607
+ * Format demo data as SQL INSERT statements
2608
+ *
2609
+ * Generates INSERT statements for database seeding. Handles:
2610
+ * - Automatic table name conversion (snake_case by default)
2611
+ * - Proper value escaping (strings, nulls, numbers, booleans)
2612
+ * - JSON serialization for arrays and objects
2613
+ * - Comment headers with record counts
2614
+ *
2615
+ * @param data - Demo data object (model names → record arrays)
2616
+ * @param options - Formatting options (tableName function)
2617
+ * @returns SQL INSERT statements as string
2618
+ *
2619
+ * @example
2620
+ * ```typescript
2621
+ * const sql = formatAsSQL(data)
2622
+ * // Output:
2623
+ * // -- Auto-generated demo data
2624
+ * // -- User (5 records)
2625
+ * // INSERT INTO user (id, name, email) VALUES ('1', 'Alice', 'alice@example.com');
2626
+ *
2627
+ * // Custom table names
2628
+ * const sql = formatAsSQL(data, {
2629
+ * tableName: name => `demo_${name.toLowerCase()}`
2630
+ * })
2631
+ * ```
2632
+ */
2633
+ declare function formatAsSQL(data: DemoData, options?: {
2634
+ tableName?: (modelName: string) => string;
2635
+ }): string;
2636
+ /**
2637
+ * Format demo data as CSV (one model at a time)
2638
+ *
2639
+ * Generates RFC 4180-compliant CSV with:
2640
+ * - Header row with all column names
2641
+ * - Proper escaping (commas, quotes, newlines)
2642
+ * - Unified columns from all records (handles sparse data)
2643
+ * - JSON serialization for complex values
2644
+ *
2645
+ * Note: CSV format only supports a single model at a time.
2646
+ * For multiple models, call this function once per model.
2647
+ *
2648
+ * @param data - Demo data object (model names → record arrays)
2649
+ * @param modelName - Name of the model to export
2650
+ * @returns CSV string (empty string if model not found or empty)
2651
+ *
2652
+ * @example
2653
+ * ```typescript
2654
+ * const userCsv = formatAsCSV(data, 'User')
2655
+ * // Output:
2656
+ * // id,name,email
2657
+ * // 1,Alice,alice@example.com
2658
+ * // 2,Bob,bob@example.com
2659
+ *
2660
+ * // Export each model to separate files
2661
+ * for (const model of Object.keys(data)) {
2662
+ * const csv = formatAsCSV(data, model)
2663
+ * writeFileSync(`${model}.csv`, csv)
2664
+ * }
2665
+ * ```
2666
+ */
2667
+ declare function formatAsCSV(data: DemoData, modelName: string): string;
2668
+
2669
+ /**
2670
+ * Main validator for demo data
2671
+ *
2672
+ * Validates data against a DemokitSchema, checking:
2673
+ * - Type correctness
2674
+ * - Format validity
2675
+ * - Referential integrity
2676
+ * - Custom constraints
2677
+ */
2678
+
2679
+ /**
2680
+ * Validate demo data against a schema
2681
+ */
2682
+ declare function validateData(data: DemoData, options: ValidatorOptions): ValidationResult;
2683
+ /**
2684
+ * Validate timestamp ordering (e.g., createdAt <= updatedAt)
2685
+ */
2686
+ declare function validateTimestampOrder(data: DemoData, rules: Array<{
2687
+ model: string;
2688
+ before: string;
2689
+ after: string;
2690
+ }>): ValidationError[];
2691
+
2692
+ /**
2693
+ * Validation rule generation from DemokitSchema
2694
+ *
2695
+ * Automatically generates validation rules based on:
2696
+ * - Property types and formats
2697
+ * - Required fields
2698
+ * - Constraints (min/max, patterns)
2699
+ * - Relationships
2700
+ */
2701
+
2702
+ /**
2703
+ * Generate all validation rules from a schema
2704
+ */
2705
+ declare function generateRulesFromSchema(schema: DemokitSchema, config?: RuleGeneratorConfig): ValidationRule[];
2706
+ /**
2707
+ * Get a human-readable description of a rule
2708
+ */
2709
+ declare function describeRule(rule: ValidationRule): string;
2710
+ /**
2711
+ * Group rules by model for easier inspection
2712
+ */
2713
+ declare function groupRulesByModel(rules: ValidationRule[]): Record<string, ValidationRule[]>;
2714
+ /**
2715
+ * Filter rules to get only relationship rules
2716
+ */
2717
+ declare function getRelationshipRules(rules: ValidationRule[]): ValidationRule[];
2718
+ /**
2719
+ * Filter rules to get only required field rules
2720
+ */
2721
+ declare function getRequiredFieldRules(rules: ValidationRule[]): ValidationRule[];
2722
+
2723
+ /**
2724
+ * Individual validation check functions
2725
+ *
2726
+ * Each function returns true if the value passes the check.
2727
+ */
2728
+ /**
2729
+ * Check if value is a string
2730
+ */
2731
+ declare function isString(value: unknown): boolean;
2732
+ /**
2733
+ * Check if value is a number (not NaN)
2734
+ */
2735
+ declare function isNumber(value: unknown): boolean;
2736
+ /**
2737
+ * Check if value is an integer
2738
+ */
2739
+ declare function isInteger(value: unknown): boolean;
2740
+ /**
2741
+ * Check if value is a boolean
2742
+ */
2743
+ declare function isBoolean(value: unknown): boolean;
2744
+ /**
2745
+ * Check if value is an array
2746
+ */
2747
+ declare function isArray(value: unknown): boolean;
2748
+ /**
2749
+ * Check if value is a plain object
2750
+ */
2751
+ declare function isObject(value: unknown): boolean;
2752
+ /**
2753
+ * Check if value is null
2754
+ */
2755
+ declare function isNull(value: unknown): boolean;
2756
+ /**
2757
+ * Check if value is undefined
2758
+ */
2759
+ declare function isUndefined(value: unknown): boolean;
2760
+ /**
2761
+ * Check if value is null or undefined
2762
+ */
2763
+ declare function isNullish(value: unknown): boolean;
2764
+ /**
2765
+ * Check if value is a valid UUID
2766
+ */
2767
+ declare function isUUID(value: unknown, strict?: boolean): boolean;
2768
+ /**
2769
+ * Check if value is a valid email format
2770
+ */
2771
+ declare function isEmail(value: unknown): boolean;
2772
+ /**
2773
+ * Check if value is a valid URL
2774
+ */
2775
+ declare function isURL(value: unknown): boolean;
2776
+ /**
2777
+ * Check if value is a valid ISO 8601 date (YYYY-MM-DD)
2778
+ */
2779
+ declare function isDate(value: unknown): boolean;
2780
+ /**
2781
+ * Check if value is a valid ISO 8601 datetime
2782
+ */
2783
+ declare function isDateTime(value: unknown): boolean;
2784
+ /**
2785
+ * Alias for isDateTime - checks ISO 8601 format
2786
+ */
2787
+ declare function isISO8601(value: unknown): boolean;
2788
+ /**
2789
+ * Check if string length is at least minLength
2790
+ */
2791
+ declare function hasMinLength(value: unknown, minLength: number): boolean;
2792
+ /**
2793
+ * Check if string length is at most maxLength
2794
+ */
2795
+ declare function hasMaxLength(value: unknown, maxLength: number): boolean;
2796
+ /**
2797
+ * Check if number is at least minimum
2798
+ */
2799
+ declare function hasMinimum(value: unknown, minimum: number): boolean;
2800
+ /**
2801
+ * Check if number is at most maximum
2802
+ */
2803
+ declare function hasMaximum(value: unknown, maximum: number): boolean;
2804
+ /**
2805
+ * Check if string matches a regex pattern
2806
+ */
2807
+ declare function matchesPattern(value: unknown, pattern: string | RegExp): boolean;
2808
+ /**
2809
+ * Check if value is in an enum array
2810
+ */
2811
+ declare function isInEnum(value: unknown, enumValues: unknown[]): boolean;
2812
+ /**
2813
+ * Check if two values are equal
2814
+ */
2815
+ declare function equals(value: unknown, expected: unknown): boolean;
2816
+ /**
2817
+ * Check if a date/datetime is before or equal to another
2818
+ */
2819
+ declare function isBeforeOrEqual(value: unknown, other: unknown): boolean;
2820
+ /**
2821
+ * Check if a date/datetime is after or equal to another
2822
+ */
2823
+ declare function isAfterOrEqual(value: unknown, other: unknown): boolean;
2824
+ /**
2825
+ * Check if array is not empty
2826
+ */
2827
+ declare function isArrayNotEmpty(value: unknown): boolean;
2828
+ /**
2829
+ * Check if array has at least minLength items
2830
+ */
2831
+ declare function hasArrayMinLength(value: unknown, minLength: number): boolean;
2832
+ /**
2833
+ * Check if array has at most maxLength items
2834
+ */
2835
+ declare function hasArrayMaxLength(value: unknown, maxLength: number): boolean;
2836
+ /**
2837
+ * Check if a string is empty or only whitespace
2838
+ */
2839
+ declare function isEmptyString(value: unknown): boolean;
2840
+ /**
2841
+ * Get the type name of a value (for error messages)
2842
+ */
2843
+ declare function getTypeName(value: unknown): string;
2844
+
2845
+ declare const checks_equals: typeof equals;
2846
+ declare const checks_getTypeName: typeof getTypeName;
2847
+ declare const checks_hasArrayMaxLength: typeof hasArrayMaxLength;
2848
+ declare const checks_hasArrayMinLength: typeof hasArrayMinLength;
2849
+ declare const checks_hasMaxLength: typeof hasMaxLength;
2850
+ declare const checks_hasMaximum: typeof hasMaximum;
2851
+ declare const checks_hasMinLength: typeof hasMinLength;
2852
+ declare const checks_hasMinimum: typeof hasMinimum;
2853
+ declare const checks_isAfterOrEqual: typeof isAfterOrEqual;
2854
+ declare const checks_isArray: typeof isArray;
2855
+ declare const checks_isArrayNotEmpty: typeof isArrayNotEmpty;
2856
+ declare const checks_isBeforeOrEqual: typeof isBeforeOrEqual;
2857
+ declare const checks_isBoolean: typeof isBoolean;
2858
+ declare const checks_isDate: typeof isDate;
2859
+ declare const checks_isDateTime: typeof isDateTime;
2860
+ declare const checks_isEmail: typeof isEmail;
2861
+ declare const checks_isEmptyString: typeof isEmptyString;
2862
+ declare const checks_isISO8601: typeof isISO8601;
2863
+ declare const checks_isInEnum: typeof isInEnum;
2864
+ declare const checks_isInteger: typeof isInteger;
2865
+ declare const checks_isNull: typeof isNull;
2866
+ declare const checks_isNullish: typeof isNullish;
2867
+ declare const checks_isNumber: typeof isNumber;
2868
+ declare const checks_isObject: typeof isObject;
2869
+ declare const checks_isString: typeof isString;
2870
+ declare const checks_isURL: typeof isURL;
2871
+ declare const checks_isUUID: typeof isUUID;
2872
+ declare const checks_isUndefined: typeof isUndefined;
2873
+ declare const checks_matchesPattern: typeof matchesPattern;
2874
+ declare namespace checks {
2875
+ export { checks_equals as equals, checks_getTypeName as getTypeName, checks_hasArrayMaxLength as hasArrayMaxLength, checks_hasArrayMinLength as hasArrayMinLength, checks_hasMaxLength as hasMaxLength, checks_hasMaximum as hasMaximum, checks_hasMinLength as hasMinLength, checks_hasMinimum as hasMinimum, checks_isAfterOrEqual as isAfterOrEqual, checks_isArray as isArray, checks_isArrayNotEmpty as isArrayNotEmpty, checks_isBeforeOrEqual as isBeforeOrEqual, checks_isBoolean as isBoolean, checks_isDate as isDate, checks_isDateTime as isDateTime, checks_isEmail as isEmail, checks_isEmptyString as isEmptyString, checks_isISO8601 as isISO8601, checks_isInEnum as isInEnum, checks_isInteger as isInteger, checks_isNull as isNull, checks_isNullish as isNullish, checks_isNumber as isNumber, checks_isObject as isObject, checks_isString as isString, checks_isURL as isURL, checks_isUUID as isUUID, checks_isUndefined as isUndefined, checks_matchesPattern as matchesPattern };
2876
+ }
2877
+
2878
+ export { type AppContext, type BooleanFieldRule, type Character, type CloudFixtureResponse, type CodebaseFile, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, type DataModel, type Dataset, type DatasetFieldRule, type DemoData, type DemoInterceptor, type DemoKitConfig, type DemoKitRemoteConfig, type DemoNarrative, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type DemokitSchema, type Endpoint, type EndpointMapping, type EntityContext, type EnumFieldRule, FORMAT_PATTERNS, FORMAT_PRIORITY, type FieldRule, FileParseError, type FixtureHandler, type FixtureMap, FormatDetectionError, type FormatDetectionPatterns, type FormatDetectionResult, type GenerationLevel, type GenerationMetadata, type GenerationOptions, type GenerationResult, type GenerationRulesConfig, type HttpMethod, type IntegerFieldRule, type MatchResult, type MergeConflict, type MergeOptions, type MergeResult, type MetricTarget, type ModelData, type ModelSourceMap, type ModelType, type NumberFieldRule, type OutputOptions, type ParameterDef, type ParseCSVResult, type ParseOptions, type ParseResult, type ParseSchemaOptions, type ParseWarning, type ParsedPattern, type PropertyDef, type PropertyDiff, type PropertyType, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type Relationship, type RelationshipDetectionMethod, type RelationshipSide, type RelationshipTarget, type RelationshipType, type RemoteConfig, RemoteFetchError, type RemoteLoadingState, type RequestBody, type RequestContext, type ResponseDef, type RuleGeneratorConfig, type SafeResult, type SchemaDiff, type SchemaDiffItem, type SchemaFormat, type SchemaInfo, SchemaMergeError, SchemaParseError, type SchemaRef, type SchemaSource, SchemaValidationError, type SessionState, type StringFieldRule, type TimelineEvent, type ValidationCheck, type ValidationError, type ValidationErrorType, type ValidationResult, type ValidationRule, type ValidationStats, type ValidationWarning, type ValidationWarningType, type ValidatorOptions, aggregateWarnings, buildFixtureMap, checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };