@constructive-io/data 0.3.0 → 0.6.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.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var graphql = require('graphql');
4
4
  var Ajv = require('ajv');
5
+ var errors = require('@constructive-io/errors');
5
6
 
6
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
8
 
@@ -48,7 +49,7 @@ var require_inflection = __commonJS({
48
49
  exports.titleize = titleize;
49
50
  exports.demodulize = demodulize;
50
51
  exports.tableize = tableize;
51
- exports.classify = classify;
52
+ exports.classify = classify2;
52
53
  exports.foreignKey = foreignKey;
53
54
  exports.ordinalize = ordinalize;
54
55
  exports.transform = transform;
@@ -687,7 +688,7 @@ var require_inflection = __commonJS({
687
688
  str = pluralize5(str);
688
689
  return str;
689
690
  }
690
- function classify(str) {
691
+ function classify2(str) {
691
692
  str = camelize(str);
692
693
  str = singularize5(str);
693
694
  return str;
@@ -731,7 +732,7 @@ var require_inflection = __commonJS({
731
732
  titleize,
732
733
  demodulize,
733
734
  tableize,
734
- classify,
735
+ classify: classify2,
735
736
  foreignKey,
736
737
  ordinalize
737
738
  };
@@ -3110,7 +3111,7 @@ function getAvailableRelations(table) {
3110
3111
  return relations;
3111
3112
  }
3112
3113
  function validateFieldSelection(selection, table) {
3113
- const errors = [];
3114
+ const errors2 = [];
3114
3115
  if (typeof selection === "string") {
3115
3116
  return { isValid: true, errors: [] };
3116
3117
  }
@@ -3118,39 +3119,39 @@ function validateFieldSelection(selection, table) {
3118
3119
  if (selection.select) {
3119
3120
  selection.select.forEach((field2) => {
3120
3121
  if (!tableFieldNames.includes(field2)) {
3121
- errors.push(`Field '${field2}' does not exist in table '${table.name}'`);
3122
+ errors2.push(`Field '${field2}' does not exist in table '${table.name}'`);
3122
3123
  }
3123
3124
  });
3124
3125
  }
3125
3126
  if (selection.includeRelations) {
3126
3127
  selection.includeRelations.forEach((field2) => {
3127
3128
  if (!isRelationalField2(field2, table)) {
3128
- errors.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3129
+ errors2.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3129
3130
  }
3130
3131
  });
3131
3132
  }
3132
3133
  if (selection.include) {
3133
3134
  Object.keys(selection.include).forEach((field2) => {
3134
3135
  if (!isRelationalField2(field2, table)) {
3135
- errors.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3136
+ errors2.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3136
3137
  }
3137
3138
  });
3138
3139
  }
3139
3140
  if (selection.exclude) {
3140
3141
  selection.exclude.forEach((field2) => {
3141
3142
  if (!tableFieldNames.includes(field2)) {
3142
- errors.push(`Exclude field '${field2}' does not exist in table '${table.name}'`);
3143
+ errors2.push(`Exclude field '${field2}' does not exist in table '${table.name}'`);
3143
3144
  }
3144
3145
  });
3145
3146
  }
3146
3147
  if (selection.maxDepth !== void 0) {
3147
3148
  if (typeof selection.maxDepth !== "number" || selection.maxDepth < 0 || selection.maxDepth > 5) {
3148
- errors.push("maxDepth must be a number between 0 and 5");
3149
+ errors2.push("maxDepth must be a number between 0 and 5");
3149
3150
  }
3150
3151
  }
3151
3152
  return {
3152
- isValid: errors.length === 0,
3153
- errors
3153
+ isValid: errors2.length === 0,
3154
+ errors: errors2
3154
3155
  };
3155
3156
  }
3156
3157
 
@@ -4281,39 +4282,6 @@ function normalizeSchemaEnumInputValues(input, table, mappings) {
4281
4282
  }
4282
4283
  return normalized;
4283
4284
  }
4284
-
4285
- // src/error-handler.ts
4286
- var DataErrorType2 = {
4287
- // Network/Connection errors
4288
- NETWORK_ERROR: "NETWORK_ERROR",
4289
- TIMEOUT_ERROR: "TIMEOUT_ERROR",
4290
- // Validation errors
4291
- VALIDATION_FAILED: "VALIDATION_FAILED",
4292
- REQUIRED_FIELD_MISSING: "REQUIRED_FIELD_MISSING",
4293
- INVALID_MUTATION_DATA: "INVALID_MUTATION_DATA",
4294
- // Query errors
4295
- QUERY_GENERATION_FAILED: "QUERY_GENERATION_FAILED",
4296
- QUERY_EXECUTION_FAILED: "QUERY_EXECUTION_FAILED",
4297
- // Permission errors
4298
- UNAUTHORIZED: "UNAUTHORIZED",
4299
- FORBIDDEN: "FORBIDDEN",
4300
- // Schema errors
4301
- TABLE_NOT_FOUND: "TABLE_NOT_FOUND",
4302
- // Request errors
4303
- BAD_REQUEST: "BAD_REQUEST",
4304
- NOT_FOUND: "NOT_FOUND",
4305
- // GraphQL-specific errors
4306
- GRAPHQL_ERROR: "GRAPHQL_ERROR",
4307
- // PostgreSQL constraint errors (surfaced via PostGraphile)
4308
- UNIQUE_VIOLATION: "UNIQUE_VIOLATION",
4309
- FOREIGN_KEY_VIOLATION: "FOREIGN_KEY_VIOLATION",
4310
- NOT_NULL_VIOLATION: "NOT_NULL_VIOLATION",
4311
- CHECK_VIOLATION: "CHECK_VIOLATION",
4312
- EXCLUSION_VIOLATION: "EXCLUSION_VIOLATION",
4313
- // Generic errors
4314
- UNKNOWN_ERROR: "UNKNOWN_ERROR"
4315
- };
4316
- var errorWithCaptureStackTrace = Error;
4317
4285
  function wait(ms) {
4318
4286
  if (ms <= 0) return Promise.resolve();
4319
4287
  const scheduler = globalThis.setTimeout;
@@ -4322,376 +4290,20 @@ function wait(ms) {
4322
4290
  scheduler(resolve, ms);
4323
4291
  });
4324
4292
  }
4325
- var DataError2 = class _DataError extends Error {
4326
- type;
4327
- code;
4328
- originalError;
4329
- context;
4330
- tableName;
4331
- fieldName;
4332
- constraint;
4333
- constructor(type, message, options = {}) {
4334
- super(message);
4335
- this.name = "DataError";
4336
- this.type = type;
4337
- this.code = options.code;
4338
- this.originalError = options.originalError;
4339
- this.context = options.context;
4340
- this.tableName = options.tableName;
4341
- this.fieldName = options.fieldName;
4342
- this.constraint = options.constraint;
4343
- if (errorWithCaptureStackTrace.captureStackTrace) {
4344
- errorWithCaptureStackTrace.captureStackTrace(this, _DataError);
4345
- }
4346
- }
4347
- /**
4348
- * Get a user-friendly error message.
4349
- * Checks constraint-specific messages first, then falls back to generic messages.
4350
- */
4351
- getUserMessage() {
4352
- if (this.constraint) {
4353
- const constraintMsg = getConstraintMessage(this.constraint);
4354
- if (constraintMsg) return constraintMsg;
4355
- }
4356
- switch (this.type) {
4357
- case DataErrorType2.NETWORK_ERROR:
4358
- return "Network error. Please check your connection and try again.";
4359
- case DataErrorType2.TIMEOUT_ERROR:
4360
- return "Request timed out. Please try again.";
4361
- case DataErrorType2.UNAUTHORIZED:
4362
- return "You are not authorized. Please log in and try again.";
4363
- case DataErrorType2.FORBIDDEN:
4364
- return "You do not have permission to access this resource.";
4365
- case DataErrorType2.VALIDATION_FAILED:
4366
- return "Validation failed. Please check your input and try again.";
4367
- case DataErrorType2.REQUIRED_FIELD_MISSING:
4368
- return this.fieldName ? `The field "${this.fieldName}" is required.` : "A required field is missing. Please check your input.";
4369
- case DataErrorType2.INVALID_MUTATION_DATA:
4370
- return "Invalid input. Please check your data and try again.";
4371
- case DataErrorType2.QUERY_GENERATION_FAILED:
4372
- return "Query validation failed. Please check your request.";
4373
- case DataErrorType2.QUERY_EXECUTION_FAILED:
4374
- return "Query execution failed. Please try again.";
4375
- case DataErrorType2.TABLE_NOT_FOUND:
4376
- return "The requested table was not found.";
4377
- case DataErrorType2.BAD_REQUEST:
4378
- return this.message || "Invalid request.";
4379
- case DataErrorType2.NOT_FOUND:
4380
- return "The requested resource was not found.";
4381
- case DataErrorType2.UNIQUE_VIOLATION:
4382
- return this.fieldName ? `A record with this ${this.fieldName} already exists.` : "A record with this value already exists.";
4383
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4384
- return "This record cannot be saved because it references a record that does not exist.";
4385
- case DataErrorType2.NOT_NULL_VIOLATION:
4386
- return this.fieldName ? `The field "${this.fieldName}" cannot be empty.` : "A required field cannot be empty.";
4387
- case DataErrorType2.CHECK_VIOLATION:
4388
- return this.fieldName ? `The value for "${this.fieldName}" is not valid.` : "The value does not meet the required constraints.";
4389
- case DataErrorType2.EXCLUSION_VIOLATION:
4390
- return "This record conflicts with an existing record.";
4391
- default:
4392
- return this.message || "An unexpected error occurred.";
4393
- }
4394
- }
4395
- /**
4396
- * Check if this error is retryable
4397
- */
4398
- isRetryable() {
4399
- return this.type === DataErrorType2.NETWORK_ERROR || this.type === DataErrorType2.TIMEOUT_ERROR;
4400
- }
4401
- /**
4402
- * Get error details for logging
4403
- */
4404
- getLogDetails() {
4405
- return {
4406
- type: this.type,
4407
- message: this.message,
4408
- code: this.code,
4409
- tableName: this.tableName,
4410
- fieldName: this.fieldName,
4411
- context: this.context,
4412
- stack: this.stack,
4413
- originalError: this.originalError ? {
4414
- name: this.originalError.name,
4415
- message: this.originalError.message
4416
- } : void 0
4417
- };
4418
- }
4419
- };
4420
- var createDataError = {
4421
- networkError: (originalError, tableName) => new DataError2(DataErrorType2.NETWORK_ERROR, "Network error occurred", { originalError, tableName }),
4422
- timeoutError: (originalError, tableName) => new DataError2(DataErrorType2.TIMEOUT_ERROR, "Request timed out", { originalError, tableName }),
4423
- validationFailed: (tableName, validationErrors) => new DataError2(
4424
- DataErrorType2.VALIDATION_FAILED,
4425
- `Validation failed: ${validationErrors.join(", ")}`,
4426
- { tableName, context: { validationErrors } }
4427
- ),
4428
- requiredFieldMissing: (fieldName, tableName) => new DataError2(DataErrorType2.REQUIRED_FIELD_MISSING, `Required field ${fieldName} is missing`, {
4429
- tableName,
4430
- fieldName
4431
- }),
4432
- unauthorized: (message = "Authentication required", tableName) => new DataError2(DataErrorType2.UNAUTHORIZED, message, { tableName }),
4433
- forbidden: (tableName) => new DataError2(DataErrorType2.FORBIDDEN, "Access forbidden", { tableName }),
4434
- queryGenerationFailed: (message, tableName, code) => new DataError2(DataErrorType2.QUERY_GENERATION_FAILED, message, { tableName, code }),
4435
- queryExecutionFailed: (message, tableName, code) => new DataError2(DataErrorType2.QUERY_EXECUTION_FAILED, message, { tableName, code }),
4436
- tableNotFound: (message = "Table not found", tableName, code) => new DataError2(DataErrorType2.TABLE_NOT_FOUND, message, { tableName, code }),
4437
- invalidMutationData: (message, tableName, code, context) => new DataError2(DataErrorType2.INVALID_MUTATION_DATA, message, { tableName, code, context }),
4438
- // PostgreSQL constraint violations
4439
- uniqueViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.UNIQUE_VIOLATION, message, { tableName, fieldName, constraint, code: "23505" }),
4440
- foreignKeyViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.FOREIGN_KEY_VIOLATION, message, { tableName, fieldName, constraint, code: "23503" }),
4441
- notNullViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.NOT_NULL_VIOLATION, message, { tableName, fieldName, constraint, code: "23502" }),
4442
- checkViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.CHECK_VIOLATION, message, { tableName, fieldName, constraint, code: "23514" }),
4443
- exclusionViolation: (message, tableName, constraint) => new DataError2(DataErrorType2.EXCLUSION_VIOLATION, message, { tableName, constraint, code: "23P01" }),
4444
- unknown: (originalError, tableName) => new DataError2(DataErrorType2.UNKNOWN_ERROR, originalError.message, { originalError, tableName })
4445
- };
4446
- var createError2 = {
4447
- network: (originalError) => createDataError.networkError(originalError),
4448
- timeout: (originalError) => createDataError.timeoutError(originalError),
4449
- unauthorized: (message = "Authentication required") => createDataError.unauthorized(message),
4450
- forbidden: (message = "Access forbidden") => new DataError2(DataErrorType2.FORBIDDEN, message),
4451
- badRequest: (message, code) => new DataError2(DataErrorType2.BAD_REQUEST, message, { code }),
4452
- notFound: (message = "Resource not found") => new DataError2(DataErrorType2.NOT_FOUND, message),
4453
- graphql: (message, code) => new DataError2(DataErrorType2.GRAPHQL_ERROR, message, { code }),
4454
- unknown: (originalError) => createDataError.unknown(originalError)
4455
- };
4456
- var PG_ERROR_CODES2 = {
4457
- // Class 23 - Integrity Constraint Violation
4458
- UNIQUE_VIOLATION: "23505",
4459
- FOREIGN_KEY_VIOLATION: "23503",
4460
- NOT_NULL_VIOLATION: "23502",
4461
- CHECK_VIOLATION: "23514",
4462
- EXCLUSION_VIOLATION: "23P01",
4463
- // Class 22 - Data Exception
4464
- NUMERIC_VALUE_OUT_OF_RANGE: "22003",
4465
- STRING_DATA_RIGHT_TRUNCATION: "22001",
4466
- INVALID_TEXT_REPRESENTATION: "22P02",
4467
- DATETIME_FIELD_OVERFLOW: "22008",
4468
- // Class 42 - Syntax Error or Access Rule Violation
4469
- UNDEFINED_TABLE: "42P01",
4470
- UNDEFINED_COLUMN: "42703",
4471
- INSUFFICIENT_PRIVILEGE: "42501",
4472
- // Class 53 - Insufficient Resources
4473
- DISK_FULL: "53100",
4474
- OUT_OF_MEMORY: "53200",
4475
- TOO_MANY_CONNECTIONS: "53300"
4476
- };
4477
- function parseGraphQLErrorCode(code) {
4478
- if (!code) return DataErrorType2.UNKNOWN_ERROR;
4479
- const normalized = code.toUpperCase();
4480
- if (normalized === "UNAUTHENTICATED") return DataErrorType2.UNAUTHORIZED;
4481
- if (normalized === "BAD_TOKEN_DEFINITION") return DataErrorType2.UNAUTHORIZED;
4482
- if (normalized === "FORBIDDEN") return DataErrorType2.FORBIDDEN;
4483
- if (normalized === "GRAPHQL_VALIDATION_FAILED") return DataErrorType2.QUERY_GENERATION_FAILED;
4484
- if (normalized === "INTERNAL_ERROR" || normalized === "INTERNAL_SERVER_ERROR") return DataErrorType2.QUERY_EXECUTION_FAILED;
4485
- if (normalized === "NOT_FOUND") return DataErrorType2.TABLE_NOT_FOUND;
4486
- if (normalized === "INVALID_INPUT") return DataErrorType2.INVALID_MUTATION_DATA;
4487
- if (code === PG_ERROR_CODES2.UNIQUE_VIOLATION) return DataErrorType2.UNIQUE_VIOLATION;
4488
- if (code === PG_ERROR_CODES2.FOREIGN_KEY_VIOLATION) return DataErrorType2.FOREIGN_KEY_VIOLATION;
4489
- if (code === PG_ERROR_CODES2.NOT_NULL_VIOLATION) return DataErrorType2.NOT_NULL_VIOLATION;
4490
- if (code === PG_ERROR_CODES2.CHECK_VIOLATION) return DataErrorType2.CHECK_VIOLATION;
4491
- if (code === PG_ERROR_CODES2.EXCLUSION_VIOLATION) return DataErrorType2.EXCLUSION_VIOLATION;
4492
- if (code === PG_ERROR_CODES2.INSUFFICIENT_PRIVILEGE) return DataErrorType2.FORBIDDEN;
4493
- if (code === PG_ERROR_CODES2.UNDEFINED_TABLE) return DataErrorType2.TABLE_NOT_FOUND;
4494
- if (code === PG_ERROR_CODES2.UNDEFINED_COLUMN) return DataErrorType2.INVALID_MUTATION_DATA;
4495
- if (code === PG_ERROR_CODES2.NUMERIC_VALUE_OUT_OF_RANGE) return DataErrorType2.VALIDATION_FAILED;
4496
- if (code === PG_ERROR_CODES2.STRING_DATA_RIGHT_TRUNCATION) return DataErrorType2.VALIDATION_FAILED;
4497
- if (code === PG_ERROR_CODES2.INVALID_TEXT_REPRESENTATION) return DataErrorType2.VALIDATION_FAILED;
4498
- if (code === PG_ERROR_CODES2.DATETIME_FIELD_OVERFLOW) return DataErrorType2.VALIDATION_FAILED;
4499
- return DataErrorType2.UNKNOWN_ERROR;
4500
- }
4501
- var Errors = {
4502
- /** Map a raw extensions.code to its DataErrorType */
4503
- parse(code) {
4504
- return parseGraphQLErrorCode(code);
4505
- },
4506
- /** Check if a raw extensions.code matches a DataErrorType */
4507
- is(code, type) {
4508
- if (typeof code !== "string") return false;
4509
- return parseGraphQLErrorCode(code) === type;
4510
- },
4511
- /** Check if any error object matches a DataErrorType */
4512
- match(error, type) {
4513
- if (error instanceof DataError2) return error.type === type;
4514
- return parseGraphQLError2(error).type === type;
4515
- },
4516
- /** Parse any error into a classified DataError */
4517
- from(error, tableName) {
4518
- return parseGraphQLError2(error, tableName);
4519
- }
4520
- };
4521
- function isGraphQLRequestErrorLike(error) {
4522
- return error instanceof Error && error.name === "GraphQLRequestError" && Array.isArray(error.errors);
4293
+ function getErrorCode(error) {
4294
+ return errors.parse(error).code;
4523
4295
  }
4524
- function isGraphQLErrorLike(value) {
4525
- return !!value && typeof value === "object" && "message" in value && typeof value.message === "string" && !(value instanceof Error);
4296
+ var AUTH_ERROR_CODES = /* @__PURE__ */ new Set(["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"]);
4297
+ var AUTH_MESSAGE_PATTERN = /unauthenticated|unauthorized|not authorized|authentication|session expired|token expired/;
4298
+ function isAuthenticationError(error) {
4299
+ const parsed = errors.parse(error);
4300
+ if (parsed.code && AUTH_ERROR_CODES.has(parsed.code)) return true;
4301
+ return AUTH_MESSAGE_PATTERN.test((parsed.rawMessage ?? "").toLowerCase());
4526
4302
  }
4527
- function extractCodeFromMessage(message) {
4528
- const match = message.match(/\(\s*Code:\s*([A-Za-z0-9_]+)\s*\)/);
4529
- return match?.[1];
4530
- }
4531
- function classifyByMessage(message) {
4532
- const lower = message.toLowerCase();
4533
- if (lower.includes("timeout") || lower.includes("timed out") || lower.includes("aborted")) {
4534
- return DataErrorType2.TIMEOUT_ERROR;
4535
- }
4536
- if (lower.includes("network") || lower.includes("fetch") || lower.includes("failed to fetch")) {
4537
- return DataErrorType2.NETWORK_ERROR;
4538
- }
4539
- if (lower.includes("unauthenticated") || lower.includes("unauthorized") || lower.includes("not authorized") || lower.includes("authentication")) {
4540
- return DataErrorType2.UNAUTHORIZED;
4541
- }
4542
- if (lower.includes("forbidden") || lower.includes("access denied") || lower.includes("permission")) {
4543
- return DataErrorType2.FORBIDDEN;
4544
- }
4545
- if (lower.includes("validation")) {
4546
- return DataErrorType2.VALIDATION_FAILED;
4547
- }
4548
- if (lower.includes("duplicate key") || lower.includes("already exists") || lower.includes("unique constraint")) {
4549
- return DataErrorType2.UNIQUE_VIOLATION;
4550
- }
4551
- if (lower.includes("foreign key constraint") || lower.includes("violates foreign key")) {
4552
- return DataErrorType2.FOREIGN_KEY_VIOLATION;
4553
- }
4554
- if (lower.includes("not-null constraint") || lower.includes("null value in column")) {
4555
- return DataErrorType2.NOT_NULL_VIOLATION;
4556
- }
4557
- if (lower.includes("check constraint")) {
4558
- return DataErrorType2.CHECK_VIOLATION;
4559
- }
4560
- return DataErrorType2.UNKNOWN_ERROR;
4561
- }
4562
- function extractPostgresDetails(extensions) {
4563
- if (!extensions) return {};
4564
- return {
4565
- constraint: typeof extensions.constraint === "string" ? extensions.constraint : void 0,
4566
- column: typeof extensions.column === "string" ? extensions.column : void 0,
4567
- table: typeof extensions.table === "string" ? extensions.table : void 0,
4568
- detail: typeof extensions.detail === "string" ? extensions.detail : void 0
4569
- };
4570
- }
4571
- function extractFieldFromError(message, constraint, column) {
4572
- if (column) return column;
4573
- const columnMatch = message.match(/column\s+"?([a-z_][a-z0-9_]*)"?/i);
4574
- if (columnMatch) return columnMatch[1];
4575
- if (constraint) {
4576
- const constraintMatch = constraint.match(/_([a-z_][a-z0-9_]*)_(?:key|fkey|check|pkey)$/i);
4577
- if (constraintMatch) return constraintMatch[1];
4578
- }
4579
- const keyMatch = message.match(/Key\s+\(([a-z_][a-z0-9_]*)\)/i);
4580
- if (keyMatch) return keyMatch[1];
4581
- return void 0;
4582
- }
4583
- function parseGraphQLError2(error, tableName) {
4584
- if (error instanceof DataError2) {
4585
- return error;
4586
- }
4587
- if (isGraphQLRequestErrorLike(error) && error.errors.length > 0) {
4588
- return parseGraphQLError2(error.errors[0], tableName);
4589
- }
4590
- if (isGraphQLErrorLike(error)) {
4591
- const extCode = error.extensions?.code;
4592
- const mappedFromExt = parseGraphQLErrorCode(extCode);
4593
- const pgDetails = extractPostgresDetails(error.extensions);
4594
- const effectiveTable = tableName || pgDetails.table;
4595
- const fieldName = extractFieldFromError(error.message, pgDetails.constraint, pgDetails.column);
4596
- if (mappedFromExt !== DataErrorType2.UNKNOWN_ERROR) {
4597
- switch (mappedFromExt) {
4598
- case DataErrorType2.UNAUTHORIZED:
4599
- return createDataError.unauthorized(error.message, effectiveTable);
4600
- case DataErrorType2.FORBIDDEN:
4601
- return createDataError.forbidden(effectiveTable);
4602
- case DataErrorType2.QUERY_GENERATION_FAILED:
4603
- return createDataError.queryGenerationFailed(error.message, effectiveTable, extCode);
4604
- case DataErrorType2.QUERY_EXECUTION_FAILED:
4605
- return createDataError.queryExecutionFailed(error.message, effectiveTable, extCode);
4606
- case DataErrorType2.TABLE_NOT_FOUND:
4607
- return createDataError.tableNotFound(error.message, effectiveTable, extCode);
4608
- case DataErrorType2.INVALID_MUTATION_DATA:
4609
- return createDataError.invalidMutationData(error.message, effectiveTable, extCode, error.extensions);
4610
- // PostgreSQL constraint violations
4611
- case DataErrorType2.UNIQUE_VIOLATION:
4612
- return createDataError.uniqueViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4613
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4614
- return createDataError.foreignKeyViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4615
- case DataErrorType2.NOT_NULL_VIOLATION:
4616
- return createDataError.notNullViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4617
- case DataErrorType2.CHECK_VIOLATION:
4618
- return createDataError.checkViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4619
- case DataErrorType2.EXCLUSION_VIOLATION:
4620
- return createDataError.exclusionViolation(error.message, effectiveTable, pgDetails.constraint);
4621
- case DataErrorType2.VALIDATION_FAILED:
4622
- return createDataError.validationFailed(effectiveTable, [error.message]);
4623
- }
4624
- }
4625
- const fallbackType = classifyByMessage(error.message);
4626
- switch (fallbackType) {
4627
- case DataErrorType2.VALIDATION_FAILED:
4628
- return createDataError.validationFailed(effectiveTable, [error.message]);
4629
- case DataErrorType2.FORBIDDEN:
4630
- return createDataError.forbidden(effectiveTable);
4631
- case DataErrorType2.UNAUTHORIZED:
4632
- return createDataError.unauthorized("Authentication required", effectiveTable);
4633
- case DataErrorType2.TIMEOUT_ERROR:
4634
- return createDataError.timeoutError(new Error(error.message), effectiveTable);
4635
- case DataErrorType2.NETWORK_ERROR:
4636
- return createDataError.networkError(new Error(error.message), effectiveTable);
4637
- case DataErrorType2.UNIQUE_VIOLATION:
4638
- return createDataError.uniqueViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4639
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4640
- return createDataError.foreignKeyViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4641
- case DataErrorType2.NOT_NULL_VIOLATION:
4642
- return createDataError.notNullViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4643
- case DataErrorType2.CHECK_VIOLATION:
4644
- return createDataError.checkViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4645
- default:
4646
- return createDataError.unknown(new Error(error.message), effectiveTable);
4647
- }
4648
- }
4649
- if (error instanceof Error) {
4650
- const embeddedCode = extractCodeFromMessage(error.message);
4651
- const mappedFromMessageCode = parseGraphQLErrorCode(embeddedCode);
4652
- if (mappedFromMessageCode !== DataErrorType2.UNKNOWN_ERROR) {
4653
- switch (mappedFromMessageCode) {
4654
- case DataErrorType2.UNAUTHORIZED:
4655
- return createDataError.unauthorized("Authentication required. Please log in again.", tableName);
4656
- case DataErrorType2.FORBIDDEN:
4657
- return createDataError.forbidden(tableName);
4658
- default:
4659
- return new DataError2(mappedFromMessageCode, error.message, { tableName, code: embeddedCode, originalError: error });
4660
- }
4661
- }
4662
- const type = classifyByMessage(error.message);
4663
- const fieldName = extractFieldFromError(error.message);
4664
- switch (type) {
4665
- case DataErrorType2.NETWORK_ERROR:
4666
- return createDataError.networkError(error, tableName);
4667
- case DataErrorType2.TIMEOUT_ERROR:
4668
- return createDataError.timeoutError(error, tableName);
4669
- case DataErrorType2.UNAUTHORIZED:
4670
- return createDataError.unauthorized(error.message, tableName);
4671
- case DataErrorType2.FORBIDDEN:
4672
- return createDataError.forbidden(tableName);
4673
- case DataErrorType2.VALIDATION_FAILED:
4674
- return createDataError.validationFailed(tableName, [error.message]);
4675
- case DataErrorType2.UNIQUE_VIOLATION:
4676
- return createDataError.uniqueViolation(error.message, tableName, fieldName);
4677
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4678
- return createDataError.foreignKeyViolation(error.message, tableName, fieldName);
4679
- case DataErrorType2.NOT_NULL_VIOLATION:
4680
- return createDataError.notNullViolation(error.message, tableName, fieldName);
4681
- case DataErrorType2.CHECK_VIOLATION:
4682
- return createDataError.checkViolation(error.message, tableName, fieldName);
4683
- default:
4684
- return createDataError.unknown(error, tableName);
4685
- }
4686
- }
4687
- const errorMessage = typeof error === "string" ? error : "Unknown error occurred";
4688
- return createDataError.unknown(new Error(errorMessage), tableName);
4689
- }
4690
- function parseError(error) {
4691
- return parseGraphQLError2(error);
4692
- }
4693
- function handleDataError(error, tableName) {
4694
- return error instanceof DataError2 ? error : parseGraphQLError2(error, tableName);
4303
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["NETWORK_ERROR", "TIMEOUT_ERROR", "RATE_LIMITED", "TOO_MANY_REQUESTS"]);
4304
+ function isRetryable(error) {
4305
+ const { code } = errors.parse(error);
4306
+ return Boolean(code && RETRYABLE_CODES.has(code));
4695
4307
  }
4696
4308
  async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4697
4309
  let attempt = 0;
@@ -4699,10 +4311,10 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4699
4311
  try {
4700
4312
  return await fn();
4701
4313
  } catch (error) {
4702
- const dataError = parseGraphQLError2(error);
4314
+ const normalized = errors.toError(error);
4703
4315
  attempt += 1;
4704
- if (!dataError.isRetryable() || attempt >= maxRetries) {
4705
- throw dataError;
4316
+ if (!isRetryable(normalized) || attempt >= maxRetries) {
4317
+ throw normalized;
4706
4318
  }
4707
4319
  if (delayMs > 0) {
4708
4320
  await wait(delayMs);
@@ -4710,9 +4322,18 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4710
4322
  }
4711
4323
  }
4712
4324
  }
4325
+ var createError2 = {
4326
+ network: (originalError) => errors.errors.NETWORK_ERROR({}, originalError?.message),
4327
+ timeout: () => errors.errors.TIMEOUT_ERROR(),
4328
+ unauthorized: (message = "Authentication required") => errors.errors.UNAUTHENTICATED({}, message),
4329
+ forbidden: (message = "Access forbidden") => errors.errors.FORBIDDEN({}, message),
4330
+ notFound: (message = "Resource not found") => errors.errors.NOT_FOUND({}, message),
4331
+ badRequest: (message) => errors.errors.BAD_USER_INPUT({}, message),
4332
+ graphql: (message, code) => errors.toError(code ? { message, extensions: { code } } : { message }),
4333
+ unknown: (originalError) => errors.toError(originalError)
4334
+ };
4713
4335
  var CONSTRAINT_MESSAGES = {
4714
4336
  // Database provisioning
4715
- // database_schema_hash_key = unique constraint on database name hash, means name conflict
4716
4337
  database_schema_hash_key: "This database name is already taken. Please choose a different name.",
4717
4338
  database_name_key: "This database name is already taken. Please choose a different name.",
4718
4339
  database_provision_module_name_length_min: "Database name must be at least 3 characters.",
@@ -4722,8 +4343,7 @@ var CONSTRAINT_MESSAGES = {
4722
4343
  domain_subdomain_domain_key: "This subdomain is already in use for this domain.",
4723
4344
  // API constraints
4724
4345
  api_name_database_id_key: "An API with this name already exists in this database.",
4725
- // Generic patterns (checked after exact matches)
4726
- // Use * prefix for suffix matching
4346
+ // Generic suffix patterns (checked after exact matches)
4727
4347
  "*_email_key": "This email address is already registered.",
4728
4348
  "*_name_key": "This name is already taken.",
4729
4349
  "*_slug_key": "This URL slug is already in use."
@@ -4734,18 +4354,22 @@ function getConstraintMessage(constraint) {
4734
4354
  return CONSTRAINT_MESSAGES[constraint];
4735
4355
  }
4736
4356
  for (const [pattern, message] of Object.entries(CONSTRAINT_MESSAGES)) {
4737
- if (pattern.startsWith("*")) {
4738
- const suffix = pattern.slice(1);
4739
- if (constraint.endsWith(suffix)) {
4740
- return message;
4741
- }
4357
+ if (pattern.startsWith("*") && constraint.endsWith(pattern.slice(1))) {
4358
+ return message;
4742
4359
  }
4743
4360
  }
4744
4361
  return void 0;
4745
4362
  }
4746
- function getHumanReadableError(error, tableName) {
4747
- const dataError = parseGraphQLError2(error, tableName);
4748
- return dataError.getUserMessage();
4363
+ function parseError(error, locale) {
4364
+ return errors.toError(error, locale);
4365
+ }
4366
+ function parseGraphQLError2(error, locale) {
4367
+ return errors.toError(error, locale);
4368
+ }
4369
+ function getHumanReadableError(error, locale) {
4370
+ const normalized = errors.toError(error, locale);
4371
+ const constraint = typeof normalized.context?.constraint === "string" ? normalized.context.constraint : void 0;
4372
+ return getConstraintMessage(constraint) ?? normalized.message;
4749
4373
  }
4750
4374
 
4751
4375
  // src/mutation-input.ts
@@ -5215,9 +4839,9 @@ var POLICY_PROVISIONING_CONFIG = {
5215
4839
  },
5216
4840
  permission: {
5217
4841
  type: "string",
5218
- component: "permission-select",
5219
- label: "Required Permission",
5220
- description: "Optional permission the user must have"
4842
+ component: "capability-select",
4843
+ label: "Required Capability",
4844
+ description: "Optional capability the user must have"
5221
4845
  },
5222
4846
  is_admin: {
5223
4847
  type: "boolean",
@@ -5251,9 +4875,9 @@ var POLICY_PROVISIONING_CONFIG = {
5251
4875
  fieldOverrides: {
5252
4876
  permission: {
5253
4877
  type: "string",
5254
- component: "permission-select",
5255
- label: "Required Permission",
5256
- description: "Optional permission the user must have"
4878
+ component: "capability-select",
4879
+ label: "Required Capability",
4880
+ description: "Optional capability the user must have"
5257
4881
  },
5258
4882
  is_admin: {
5259
4883
  type: "boolean",
@@ -5418,8 +5042,8 @@ var POLICY_PROVISIONING_CONFIG = {
5418
5042
  },
5419
5043
  permission: {
5420
5044
  type: "string",
5421
- component: "permission-select",
5422
- label: "Required Permission"
5045
+ component: "capability-select",
5046
+ label: "Required Capability"
5423
5047
  },
5424
5048
  is_admin: {
5425
5049
  type: "boolean",
@@ -5715,15 +5339,40 @@ inflection/lib/inflection.js:
5715
5339
  *)
5716
5340
  */
5717
5341
 
5342
+ Object.defineProperty(exports, "ConstructiveError", {
5343
+ enumerable: true,
5344
+ get: function () { return errors.ConstructiveError; }
5345
+ });
5346
+ Object.defineProperty(exports, "classify", {
5347
+ enumerable: true,
5348
+ get: function () { return errors.classify; }
5349
+ });
5350
+ Object.defineProperty(exports, "errors", {
5351
+ enumerable: true,
5352
+ get: function () { return errors.errors; }
5353
+ });
5354
+ Object.defineProperty(exports, "format", {
5355
+ enumerable: true,
5356
+ get: function () { return errors.format; }
5357
+ });
5358
+ Object.defineProperty(exports, "isPublicCode", {
5359
+ enumerable: true,
5360
+ get: function () { return errors.isPublicCode; }
5361
+ });
5362
+ Object.defineProperty(exports, "parse", {
5363
+ enumerable: true,
5364
+ get: function () { return errors.parse; }
5365
+ });
5366
+ Object.defineProperty(exports, "toError", {
5367
+ enumerable: true,
5368
+ get: function () { return errors.toError; }
5369
+ });
5718
5370
  exports.CONSTRAINT_MESSAGES = CONSTRAINT_MESSAGES;
5719
5371
  exports.CRUD_OPERATIONS = CRUD_OPERATIONS;
5720
5372
  exports.CRUD_TO_PRIVILEGE = CRUD_TO_PRIVILEGE;
5721
5373
  exports.DATA_NODE_GENERATED_FIELDS = DATA_NODE_GENERATED_FIELDS;
5722
5374
  exports.DEFAULT_CONSOLE_APPLICATION_SCOPES = DEFAULT_CONSOLE_APPLICATION_SCOPES;
5723
5375
  exports.DEFAULT_CRUD_GRANT_PRIVILEGES = DEFAULT_CRUD_GRANT_PRIVILEGES;
5724
- exports.DataError = DataError2;
5725
- exports.DataErrorType = DataErrorType2;
5726
- exports.Errors = Errors;
5727
5376
  exports.MEMBERSHIP_TYPES = MEMBERSHIP_TYPES;
5728
5377
  exports.META_CONTRACT_INTROSPECTION_DOCUMENT = META_CONTRACT_INTROSPECTION_DOCUMENT;
5729
5378
  exports.META_CONTRACT_INTROSPECTION_SOURCE = META_CONTRACT_INTROSPECTION_SOURCE;
@@ -5732,7 +5381,6 @@ exports.META_CONTRACT_VERSION = META_CONTRACT_VERSION;
5732
5381
  exports.META_DOCUMENT = META_DOCUMENT;
5733
5382
  exports.META_QUERY_SOURCE = META_QUERY_SOURCE;
5734
5383
  exports.MetaContractError = MetaContractError;
5735
- exports.PG_ERROR_CODES = PG_ERROR_CODES2;
5736
5384
  exports.POLICY_PROVISIONING_CONFIG = POLICY_PROVISIONING_CONFIG;
5737
5385
  exports.QueryBuilder = QueryBuilder;
5738
5386
  exports.SCHEMA_INTROSPECTION_QUERY = SCHEMA_INTROSPECTION_QUERY;
@@ -5758,7 +5406,6 @@ exports.cleanTableToMetaObject = cleanTableToMetaObject;
5758
5406
  exports.convertFromMetaSchema = convertFromMetaSchema;
5759
5407
  exports.convertToSelectionOptions = convertToSelectionOptions;
5760
5408
  exports.createASTQueryBuilder = createASTQueryBuilder;
5761
- exports.createDataError = createDataError;
5762
5409
  exports.createError = createError2;
5763
5410
  exports.createOne = createOne;
5764
5411
  exports.deleteOne = deleteOne;
@@ -5775,6 +5422,7 @@ exports.getCustomAst = getCustomAst;
5775
5422
  exports.getCustomAstForCleanField = getCustomAstForCleanField;
5776
5423
  exports.getCustomOperations = getCustomOperations;
5777
5424
  exports.getDataNodeForPolicy = getDataNodeForPolicy;
5425
+ exports.getErrorCode = getErrorCode;
5778
5426
  exports.getFieldsRequiringColumns = getFieldsRequiringColumns;
5779
5427
  exports.getGeneratedFields = getGeneratedFields;
5780
5428
  exports.getHumanReadableError = getHumanReadableError;
@@ -5787,20 +5435,20 @@ exports.getRowIdentityDefinition = getRowIdentityDefinition;
5787
5435
  exports.getSelections = getSelections;
5788
5436
  exports.getTableOperationNames = getTableOperationNames;
5789
5437
  exports.groupCrudOperationsByConfig = groupCrudOperationsByConfig;
5790
- exports.handleDataError = handleDataError;
5791
5438
  exports.hasGeneratedFields = hasGeneratedFields;
5792
5439
  exports.injectSchemaFields = injectSchemaFields;
5793
5440
  exports.intervalAst = intervalAst;
5441
+ exports.isAuthenticationError = isAuthenticationError;
5794
5442
  exports.isGraphQLVariableValue = isGraphQLVariableValue;
5795
5443
  exports.isGraphQLVariables = isGraphQLVariables;
5796
5444
  exports.isIntervalType = isIntervalType;
5797
5445
  exports.isRelationalField = isRelationalField2;
5446
+ exports.isRetryable = isRetryable;
5798
5447
  exports.isTableOperation = isTableOperation;
5799
5448
  exports.normalizeInflectionValue = normalizeInflectionValue;
5800
5449
  exports.normalizeSchemaEnumInputValues = normalizeSchemaEnumInputValues;
5801
5450
  exports.parseError = parseError;
5802
5451
  exports.parseGraphQLError = parseGraphQLError2;
5803
- exports.parseGraphQLErrorCode = parseGraphQLErrorCode;
5804
5452
  exports.parseMetaSearchWeights = parseMetaSearchWeights;
5805
5453
  exports.patchOne = patchOne;
5806
5454
  exports.pgFieldToCamelCase = pgFieldToCamelCase;