@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.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { Kind, OperationTypeNode, print } from 'graphql';
2
2
  import Ajv from 'ajv';
3
+ import { parse, toError, errors } from '@constructive-io/errors';
4
+ export { ConstructiveError, classify, errors, format, isPublicCode, parse, toError } from '@constructive-io/errors';
3
5
 
4
6
  var __create = Object.create;
5
7
  var __defProp = Object.defineProperty;
@@ -42,7 +44,7 @@ var require_inflection = __commonJS({
42
44
  exports.titleize = titleize;
43
45
  exports.demodulize = demodulize;
44
46
  exports.tableize = tableize;
45
- exports.classify = classify;
47
+ exports.classify = classify2;
46
48
  exports.foreignKey = foreignKey;
47
49
  exports.ordinalize = ordinalize;
48
50
  exports.transform = transform;
@@ -681,7 +683,7 @@ var require_inflection = __commonJS({
681
683
  str = pluralize5(str);
682
684
  return str;
683
685
  }
684
- function classify(str) {
686
+ function classify2(str) {
685
687
  str = camelize(str);
686
688
  str = singularize5(str);
687
689
  return str;
@@ -725,7 +727,7 @@ var require_inflection = __commonJS({
725
727
  titleize,
726
728
  demodulize,
727
729
  tableize,
728
- classify,
730
+ classify: classify2,
729
731
  foreignKey,
730
732
  ordinalize
731
733
  };
@@ -3104,7 +3106,7 @@ function getAvailableRelations(table) {
3104
3106
  return relations;
3105
3107
  }
3106
3108
  function validateFieldSelection(selection, table) {
3107
- const errors = [];
3109
+ const errors2 = [];
3108
3110
  if (typeof selection === "string") {
3109
3111
  return { isValid: true, errors: [] };
3110
3112
  }
@@ -3112,39 +3114,39 @@ function validateFieldSelection(selection, table) {
3112
3114
  if (selection.select) {
3113
3115
  selection.select.forEach((field2) => {
3114
3116
  if (!tableFieldNames.includes(field2)) {
3115
- errors.push(`Field '${field2}' does not exist in table '${table.name}'`);
3117
+ errors2.push(`Field '${field2}' does not exist in table '${table.name}'`);
3116
3118
  }
3117
3119
  });
3118
3120
  }
3119
3121
  if (selection.includeRelations) {
3120
3122
  selection.includeRelations.forEach((field2) => {
3121
3123
  if (!isRelationalField2(field2, table)) {
3122
- errors.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3124
+ errors2.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3123
3125
  }
3124
3126
  });
3125
3127
  }
3126
3128
  if (selection.include) {
3127
3129
  Object.keys(selection.include).forEach((field2) => {
3128
3130
  if (!isRelationalField2(field2, table)) {
3129
- errors.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3131
+ errors2.push(`Field '${field2}' is not a relational field in table '${table.name}'`);
3130
3132
  }
3131
3133
  });
3132
3134
  }
3133
3135
  if (selection.exclude) {
3134
3136
  selection.exclude.forEach((field2) => {
3135
3137
  if (!tableFieldNames.includes(field2)) {
3136
- errors.push(`Exclude field '${field2}' does not exist in table '${table.name}'`);
3138
+ errors2.push(`Exclude field '${field2}' does not exist in table '${table.name}'`);
3137
3139
  }
3138
3140
  });
3139
3141
  }
3140
3142
  if (selection.maxDepth !== void 0) {
3141
3143
  if (typeof selection.maxDepth !== "number" || selection.maxDepth < 0 || selection.maxDepth > 5) {
3142
- errors.push("maxDepth must be a number between 0 and 5");
3144
+ errors2.push("maxDepth must be a number between 0 and 5");
3143
3145
  }
3144
3146
  }
3145
3147
  return {
3146
- isValid: errors.length === 0,
3147
- errors
3148
+ isValid: errors2.length === 0,
3149
+ errors: errors2
3148
3150
  };
3149
3151
  }
3150
3152
 
@@ -4275,39 +4277,6 @@ function normalizeSchemaEnumInputValues(input, table, mappings) {
4275
4277
  }
4276
4278
  return normalized;
4277
4279
  }
4278
-
4279
- // src/error-handler.ts
4280
- var DataErrorType2 = {
4281
- // Network/Connection errors
4282
- NETWORK_ERROR: "NETWORK_ERROR",
4283
- TIMEOUT_ERROR: "TIMEOUT_ERROR",
4284
- // Validation errors
4285
- VALIDATION_FAILED: "VALIDATION_FAILED",
4286
- REQUIRED_FIELD_MISSING: "REQUIRED_FIELD_MISSING",
4287
- INVALID_MUTATION_DATA: "INVALID_MUTATION_DATA",
4288
- // Query errors
4289
- QUERY_GENERATION_FAILED: "QUERY_GENERATION_FAILED",
4290
- QUERY_EXECUTION_FAILED: "QUERY_EXECUTION_FAILED",
4291
- // Permission errors
4292
- UNAUTHORIZED: "UNAUTHORIZED",
4293
- FORBIDDEN: "FORBIDDEN",
4294
- // Schema errors
4295
- TABLE_NOT_FOUND: "TABLE_NOT_FOUND",
4296
- // Request errors
4297
- BAD_REQUEST: "BAD_REQUEST",
4298
- NOT_FOUND: "NOT_FOUND",
4299
- // GraphQL-specific errors
4300
- GRAPHQL_ERROR: "GRAPHQL_ERROR",
4301
- // PostgreSQL constraint errors (surfaced via PostGraphile)
4302
- UNIQUE_VIOLATION: "UNIQUE_VIOLATION",
4303
- FOREIGN_KEY_VIOLATION: "FOREIGN_KEY_VIOLATION",
4304
- NOT_NULL_VIOLATION: "NOT_NULL_VIOLATION",
4305
- CHECK_VIOLATION: "CHECK_VIOLATION",
4306
- EXCLUSION_VIOLATION: "EXCLUSION_VIOLATION",
4307
- // Generic errors
4308
- UNKNOWN_ERROR: "UNKNOWN_ERROR"
4309
- };
4310
- var errorWithCaptureStackTrace = Error;
4311
4280
  function wait(ms) {
4312
4281
  if (ms <= 0) return Promise.resolve();
4313
4282
  const scheduler = globalThis.setTimeout;
@@ -4316,376 +4285,20 @@ function wait(ms) {
4316
4285
  scheduler(resolve, ms);
4317
4286
  });
4318
4287
  }
4319
- var DataError2 = class _DataError extends Error {
4320
- type;
4321
- code;
4322
- originalError;
4323
- context;
4324
- tableName;
4325
- fieldName;
4326
- constraint;
4327
- constructor(type, message, options = {}) {
4328
- super(message);
4329
- this.name = "DataError";
4330
- this.type = type;
4331
- this.code = options.code;
4332
- this.originalError = options.originalError;
4333
- this.context = options.context;
4334
- this.tableName = options.tableName;
4335
- this.fieldName = options.fieldName;
4336
- this.constraint = options.constraint;
4337
- if (errorWithCaptureStackTrace.captureStackTrace) {
4338
- errorWithCaptureStackTrace.captureStackTrace(this, _DataError);
4339
- }
4340
- }
4341
- /**
4342
- * Get a user-friendly error message.
4343
- * Checks constraint-specific messages first, then falls back to generic messages.
4344
- */
4345
- getUserMessage() {
4346
- if (this.constraint) {
4347
- const constraintMsg = getConstraintMessage(this.constraint);
4348
- if (constraintMsg) return constraintMsg;
4349
- }
4350
- switch (this.type) {
4351
- case DataErrorType2.NETWORK_ERROR:
4352
- return "Network error. Please check your connection and try again.";
4353
- case DataErrorType2.TIMEOUT_ERROR:
4354
- return "Request timed out. Please try again.";
4355
- case DataErrorType2.UNAUTHORIZED:
4356
- return "You are not authorized. Please log in and try again.";
4357
- case DataErrorType2.FORBIDDEN:
4358
- return "You do not have permission to access this resource.";
4359
- case DataErrorType2.VALIDATION_FAILED:
4360
- return "Validation failed. Please check your input and try again.";
4361
- case DataErrorType2.REQUIRED_FIELD_MISSING:
4362
- return this.fieldName ? `The field "${this.fieldName}" is required.` : "A required field is missing. Please check your input.";
4363
- case DataErrorType2.INVALID_MUTATION_DATA:
4364
- return "Invalid input. Please check your data and try again.";
4365
- case DataErrorType2.QUERY_GENERATION_FAILED:
4366
- return "Query validation failed. Please check your request.";
4367
- case DataErrorType2.QUERY_EXECUTION_FAILED:
4368
- return "Query execution failed. Please try again.";
4369
- case DataErrorType2.TABLE_NOT_FOUND:
4370
- return "The requested table was not found.";
4371
- case DataErrorType2.BAD_REQUEST:
4372
- return this.message || "Invalid request.";
4373
- case DataErrorType2.NOT_FOUND:
4374
- return "The requested resource was not found.";
4375
- case DataErrorType2.UNIQUE_VIOLATION:
4376
- return this.fieldName ? `A record with this ${this.fieldName} already exists.` : "A record with this value already exists.";
4377
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4378
- return "This record cannot be saved because it references a record that does not exist.";
4379
- case DataErrorType2.NOT_NULL_VIOLATION:
4380
- return this.fieldName ? `The field "${this.fieldName}" cannot be empty.` : "A required field cannot be empty.";
4381
- case DataErrorType2.CHECK_VIOLATION:
4382
- return this.fieldName ? `The value for "${this.fieldName}" is not valid.` : "The value does not meet the required constraints.";
4383
- case DataErrorType2.EXCLUSION_VIOLATION:
4384
- return "This record conflicts with an existing record.";
4385
- default:
4386
- return this.message || "An unexpected error occurred.";
4387
- }
4388
- }
4389
- /**
4390
- * Check if this error is retryable
4391
- */
4392
- isRetryable() {
4393
- return this.type === DataErrorType2.NETWORK_ERROR || this.type === DataErrorType2.TIMEOUT_ERROR;
4394
- }
4395
- /**
4396
- * Get error details for logging
4397
- */
4398
- getLogDetails() {
4399
- return {
4400
- type: this.type,
4401
- message: this.message,
4402
- code: this.code,
4403
- tableName: this.tableName,
4404
- fieldName: this.fieldName,
4405
- context: this.context,
4406
- stack: this.stack,
4407
- originalError: this.originalError ? {
4408
- name: this.originalError.name,
4409
- message: this.originalError.message
4410
- } : void 0
4411
- };
4412
- }
4413
- };
4414
- var createDataError = {
4415
- networkError: (originalError, tableName) => new DataError2(DataErrorType2.NETWORK_ERROR, "Network error occurred", { originalError, tableName }),
4416
- timeoutError: (originalError, tableName) => new DataError2(DataErrorType2.TIMEOUT_ERROR, "Request timed out", { originalError, tableName }),
4417
- validationFailed: (tableName, validationErrors) => new DataError2(
4418
- DataErrorType2.VALIDATION_FAILED,
4419
- `Validation failed: ${validationErrors.join(", ")}`,
4420
- { tableName, context: { validationErrors } }
4421
- ),
4422
- requiredFieldMissing: (fieldName, tableName) => new DataError2(DataErrorType2.REQUIRED_FIELD_MISSING, `Required field ${fieldName} is missing`, {
4423
- tableName,
4424
- fieldName
4425
- }),
4426
- unauthorized: (message = "Authentication required", tableName) => new DataError2(DataErrorType2.UNAUTHORIZED, message, { tableName }),
4427
- forbidden: (tableName) => new DataError2(DataErrorType2.FORBIDDEN, "Access forbidden", { tableName }),
4428
- queryGenerationFailed: (message, tableName, code) => new DataError2(DataErrorType2.QUERY_GENERATION_FAILED, message, { tableName, code }),
4429
- queryExecutionFailed: (message, tableName, code) => new DataError2(DataErrorType2.QUERY_EXECUTION_FAILED, message, { tableName, code }),
4430
- tableNotFound: (message = "Table not found", tableName, code) => new DataError2(DataErrorType2.TABLE_NOT_FOUND, message, { tableName, code }),
4431
- invalidMutationData: (message, tableName, code, context) => new DataError2(DataErrorType2.INVALID_MUTATION_DATA, message, { tableName, code, context }),
4432
- // PostgreSQL constraint violations
4433
- uniqueViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.UNIQUE_VIOLATION, message, { tableName, fieldName, constraint, code: "23505" }),
4434
- foreignKeyViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.FOREIGN_KEY_VIOLATION, message, { tableName, fieldName, constraint, code: "23503" }),
4435
- notNullViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.NOT_NULL_VIOLATION, message, { tableName, fieldName, constraint, code: "23502" }),
4436
- checkViolation: (message, tableName, fieldName, constraint) => new DataError2(DataErrorType2.CHECK_VIOLATION, message, { tableName, fieldName, constraint, code: "23514" }),
4437
- exclusionViolation: (message, tableName, constraint) => new DataError2(DataErrorType2.EXCLUSION_VIOLATION, message, { tableName, constraint, code: "23P01" }),
4438
- unknown: (originalError, tableName) => new DataError2(DataErrorType2.UNKNOWN_ERROR, originalError.message, { originalError, tableName })
4439
- };
4440
- var createError2 = {
4441
- network: (originalError) => createDataError.networkError(originalError),
4442
- timeout: (originalError) => createDataError.timeoutError(originalError),
4443
- unauthorized: (message = "Authentication required") => createDataError.unauthorized(message),
4444
- forbidden: (message = "Access forbidden") => new DataError2(DataErrorType2.FORBIDDEN, message),
4445
- badRequest: (message, code) => new DataError2(DataErrorType2.BAD_REQUEST, message, { code }),
4446
- notFound: (message = "Resource not found") => new DataError2(DataErrorType2.NOT_FOUND, message),
4447
- graphql: (message, code) => new DataError2(DataErrorType2.GRAPHQL_ERROR, message, { code }),
4448
- unknown: (originalError) => createDataError.unknown(originalError)
4449
- };
4450
- var PG_ERROR_CODES2 = {
4451
- // Class 23 - Integrity Constraint Violation
4452
- UNIQUE_VIOLATION: "23505",
4453
- FOREIGN_KEY_VIOLATION: "23503",
4454
- NOT_NULL_VIOLATION: "23502",
4455
- CHECK_VIOLATION: "23514",
4456
- EXCLUSION_VIOLATION: "23P01",
4457
- // Class 22 - Data Exception
4458
- NUMERIC_VALUE_OUT_OF_RANGE: "22003",
4459
- STRING_DATA_RIGHT_TRUNCATION: "22001",
4460
- INVALID_TEXT_REPRESENTATION: "22P02",
4461
- DATETIME_FIELD_OVERFLOW: "22008",
4462
- // Class 42 - Syntax Error or Access Rule Violation
4463
- UNDEFINED_TABLE: "42P01",
4464
- UNDEFINED_COLUMN: "42703",
4465
- INSUFFICIENT_PRIVILEGE: "42501",
4466
- // Class 53 - Insufficient Resources
4467
- DISK_FULL: "53100",
4468
- OUT_OF_MEMORY: "53200",
4469
- TOO_MANY_CONNECTIONS: "53300"
4470
- };
4471
- function parseGraphQLErrorCode(code) {
4472
- if (!code) return DataErrorType2.UNKNOWN_ERROR;
4473
- const normalized = code.toUpperCase();
4474
- if (normalized === "UNAUTHENTICATED") return DataErrorType2.UNAUTHORIZED;
4475
- if (normalized === "BAD_TOKEN_DEFINITION") return DataErrorType2.UNAUTHORIZED;
4476
- if (normalized === "FORBIDDEN") return DataErrorType2.FORBIDDEN;
4477
- if (normalized === "GRAPHQL_VALIDATION_FAILED") return DataErrorType2.QUERY_GENERATION_FAILED;
4478
- if (normalized === "INTERNAL_ERROR" || normalized === "INTERNAL_SERVER_ERROR") return DataErrorType2.QUERY_EXECUTION_FAILED;
4479
- if (normalized === "NOT_FOUND") return DataErrorType2.TABLE_NOT_FOUND;
4480
- if (normalized === "INVALID_INPUT") return DataErrorType2.INVALID_MUTATION_DATA;
4481
- if (code === PG_ERROR_CODES2.UNIQUE_VIOLATION) return DataErrorType2.UNIQUE_VIOLATION;
4482
- if (code === PG_ERROR_CODES2.FOREIGN_KEY_VIOLATION) return DataErrorType2.FOREIGN_KEY_VIOLATION;
4483
- if (code === PG_ERROR_CODES2.NOT_NULL_VIOLATION) return DataErrorType2.NOT_NULL_VIOLATION;
4484
- if (code === PG_ERROR_CODES2.CHECK_VIOLATION) return DataErrorType2.CHECK_VIOLATION;
4485
- if (code === PG_ERROR_CODES2.EXCLUSION_VIOLATION) return DataErrorType2.EXCLUSION_VIOLATION;
4486
- if (code === PG_ERROR_CODES2.INSUFFICIENT_PRIVILEGE) return DataErrorType2.FORBIDDEN;
4487
- if (code === PG_ERROR_CODES2.UNDEFINED_TABLE) return DataErrorType2.TABLE_NOT_FOUND;
4488
- if (code === PG_ERROR_CODES2.UNDEFINED_COLUMN) return DataErrorType2.INVALID_MUTATION_DATA;
4489
- if (code === PG_ERROR_CODES2.NUMERIC_VALUE_OUT_OF_RANGE) return DataErrorType2.VALIDATION_FAILED;
4490
- if (code === PG_ERROR_CODES2.STRING_DATA_RIGHT_TRUNCATION) return DataErrorType2.VALIDATION_FAILED;
4491
- if (code === PG_ERROR_CODES2.INVALID_TEXT_REPRESENTATION) return DataErrorType2.VALIDATION_FAILED;
4492
- if (code === PG_ERROR_CODES2.DATETIME_FIELD_OVERFLOW) return DataErrorType2.VALIDATION_FAILED;
4493
- return DataErrorType2.UNKNOWN_ERROR;
4494
- }
4495
- var Errors = {
4496
- /** Map a raw extensions.code to its DataErrorType */
4497
- parse(code) {
4498
- return parseGraphQLErrorCode(code);
4499
- },
4500
- /** Check if a raw extensions.code matches a DataErrorType */
4501
- is(code, type) {
4502
- if (typeof code !== "string") return false;
4503
- return parseGraphQLErrorCode(code) === type;
4504
- },
4505
- /** Check if any error object matches a DataErrorType */
4506
- match(error, type) {
4507
- if (error instanceof DataError2) return error.type === type;
4508
- return parseGraphQLError2(error).type === type;
4509
- },
4510
- /** Parse any error into a classified DataError */
4511
- from(error, tableName) {
4512
- return parseGraphQLError2(error, tableName);
4513
- }
4514
- };
4515
- function isGraphQLRequestErrorLike(error) {
4516
- return error instanceof Error && error.name === "GraphQLRequestError" && Array.isArray(error.errors);
4517
- }
4518
- function isGraphQLErrorLike(value) {
4519
- return !!value && typeof value === "object" && "message" in value && typeof value.message === "string" && !(value instanceof Error);
4520
- }
4521
- function extractCodeFromMessage(message) {
4522
- const match = message.match(/\(\s*Code:\s*([A-Za-z0-9_]+)\s*\)/);
4523
- return match?.[1];
4288
+ function getErrorCode(error) {
4289
+ return parse(error).code;
4524
4290
  }
4525
- function classifyByMessage(message) {
4526
- const lower = message.toLowerCase();
4527
- if (lower.includes("timeout") || lower.includes("timed out") || lower.includes("aborted")) {
4528
- return DataErrorType2.TIMEOUT_ERROR;
4529
- }
4530
- if (lower.includes("network") || lower.includes("fetch") || lower.includes("failed to fetch")) {
4531
- return DataErrorType2.NETWORK_ERROR;
4532
- }
4533
- if (lower.includes("unauthenticated") || lower.includes("unauthorized") || lower.includes("not authorized") || lower.includes("authentication")) {
4534
- return DataErrorType2.UNAUTHORIZED;
4535
- }
4536
- if (lower.includes("forbidden") || lower.includes("access denied") || lower.includes("permission")) {
4537
- return DataErrorType2.FORBIDDEN;
4538
- }
4539
- if (lower.includes("validation")) {
4540
- return DataErrorType2.VALIDATION_FAILED;
4541
- }
4542
- if (lower.includes("duplicate key") || lower.includes("already exists") || lower.includes("unique constraint")) {
4543
- return DataErrorType2.UNIQUE_VIOLATION;
4544
- }
4545
- if (lower.includes("foreign key constraint") || lower.includes("violates foreign key")) {
4546
- return DataErrorType2.FOREIGN_KEY_VIOLATION;
4547
- }
4548
- if (lower.includes("not-null constraint") || lower.includes("null value in column")) {
4549
- return DataErrorType2.NOT_NULL_VIOLATION;
4550
- }
4551
- if (lower.includes("check constraint")) {
4552
- return DataErrorType2.CHECK_VIOLATION;
4553
- }
4554
- return DataErrorType2.UNKNOWN_ERROR;
4291
+ var AUTH_ERROR_CODES = /* @__PURE__ */ new Set(["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"]);
4292
+ var AUTH_MESSAGE_PATTERN = /unauthenticated|unauthorized|not authorized|authentication|session expired|token expired/;
4293
+ function isAuthenticationError(error) {
4294
+ const parsed = parse(error);
4295
+ if (parsed.code && AUTH_ERROR_CODES.has(parsed.code)) return true;
4296
+ return AUTH_MESSAGE_PATTERN.test((parsed.rawMessage ?? "").toLowerCase());
4555
4297
  }
4556
- function extractPostgresDetails(extensions) {
4557
- if (!extensions) return {};
4558
- return {
4559
- constraint: typeof extensions.constraint === "string" ? extensions.constraint : void 0,
4560
- column: typeof extensions.column === "string" ? extensions.column : void 0,
4561
- table: typeof extensions.table === "string" ? extensions.table : void 0,
4562
- detail: typeof extensions.detail === "string" ? extensions.detail : void 0
4563
- };
4564
- }
4565
- function extractFieldFromError(message, constraint, column) {
4566
- if (column) return column;
4567
- const columnMatch = message.match(/column\s+"?([a-z_][a-z0-9_]*)"?/i);
4568
- if (columnMatch) return columnMatch[1];
4569
- if (constraint) {
4570
- const constraintMatch = constraint.match(/_([a-z_][a-z0-9_]*)_(?:key|fkey|check|pkey)$/i);
4571
- if (constraintMatch) return constraintMatch[1];
4572
- }
4573
- const keyMatch = message.match(/Key\s+\(([a-z_][a-z0-9_]*)\)/i);
4574
- if (keyMatch) return keyMatch[1];
4575
- return void 0;
4576
- }
4577
- function parseGraphQLError2(error, tableName) {
4578
- if (error instanceof DataError2) {
4579
- return error;
4580
- }
4581
- if (isGraphQLRequestErrorLike(error) && error.errors.length > 0) {
4582
- return parseGraphQLError2(error.errors[0], tableName);
4583
- }
4584
- if (isGraphQLErrorLike(error)) {
4585
- const extCode = error.extensions?.code;
4586
- const mappedFromExt = parseGraphQLErrorCode(extCode);
4587
- const pgDetails = extractPostgresDetails(error.extensions);
4588
- const effectiveTable = tableName || pgDetails.table;
4589
- const fieldName = extractFieldFromError(error.message, pgDetails.constraint, pgDetails.column);
4590
- if (mappedFromExt !== DataErrorType2.UNKNOWN_ERROR) {
4591
- switch (mappedFromExt) {
4592
- case DataErrorType2.UNAUTHORIZED:
4593
- return createDataError.unauthorized(error.message, effectiveTable);
4594
- case DataErrorType2.FORBIDDEN:
4595
- return createDataError.forbidden(effectiveTable);
4596
- case DataErrorType2.QUERY_GENERATION_FAILED:
4597
- return createDataError.queryGenerationFailed(error.message, effectiveTable, extCode);
4598
- case DataErrorType2.QUERY_EXECUTION_FAILED:
4599
- return createDataError.queryExecutionFailed(error.message, effectiveTable, extCode);
4600
- case DataErrorType2.TABLE_NOT_FOUND:
4601
- return createDataError.tableNotFound(error.message, effectiveTable, extCode);
4602
- case DataErrorType2.INVALID_MUTATION_DATA:
4603
- return createDataError.invalidMutationData(error.message, effectiveTable, extCode, error.extensions);
4604
- // PostgreSQL constraint violations
4605
- case DataErrorType2.UNIQUE_VIOLATION:
4606
- return createDataError.uniqueViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4607
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4608
- return createDataError.foreignKeyViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4609
- case DataErrorType2.NOT_NULL_VIOLATION:
4610
- return createDataError.notNullViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4611
- case DataErrorType2.CHECK_VIOLATION:
4612
- return createDataError.checkViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4613
- case DataErrorType2.EXCLUSION_VIOLATION:
4614
- return createDataError.exclusionViolation(error.message, effectiveTable, pgDetails.constraint);
4615
- case DataErrorType2.VALIDATION_FAILED:
4616
- return createDataError.validationFailed(effectiveTable, [error.message]);
4617
- }
4618
- }
4619
- const fallbackType = classifyByMessage(error.message);
4620
- switch (fallbackType) {
4621
- case DataErrorType2.VALIDATION_FAILED:
4622
- return createDataError.validationFailed(effectiveTable, [error.message]);
4623
- case DataErrorType2.FORBIDDEN:
4624
- return createDataError.forbidden(effectiveTable);
4625
- case DataErrorType2.UNAUTHORIZED:
4626
- return createDataError.unauthorized("Authentication required", effectiveTable);
4627
- case DataErrorType2.TIMEOUT_ERROR:
4628
- return createDataError.timeoutError(new Error(error.message), effectiveTable);
4629
- case DataErrorType2.NETWORK_ERROR:
4630
- return createDataError.networkError(new Error(error.message), effectiveTable);
4631
- case DataErrorType2.UNIQUE_VIOLATION:
4632
- return createDataError.uniqueViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4633
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4634
- return createDataError.foreignKeyViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4635
- case DataErrorType2.NOT_NULL_VIOLATION:
4636
- return createDataError.notNullViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4637
- case DataErrorType2.CHECK_VIOLATION:
4638
- return createDataError.checkViolation(error.message, effectiveTable, fieldName, pgDetails.constraint);
4639
- default:
4640
- return createDataError.unknown(new Error(error.message), effectiveTable);
4641
- }
4642
- }
4643
- if (error instanceof Error) {
4644
- const embeddedCode = extractCodeFromMessage(error.message);
4645
- const mappedFromMessageCode = parseGraphQLErrorCode(embeddedCode);
4646
- if (mappedFromMessageCode !== DataErrorType2.UNKNOWN_ERROR) {
4647
- switch (mappedFromMessageCode) {
4648
- case DataErrorType2.UNAUTHORIZED:
4649
- return createDataError.unauthorized("Authentication required. Please log in again.", tableName);
4650
- case DataErrorType2.FORBIDDEN:
4651
- return createDataError.forbidden(tableName);
4652
- default:
4653
- return new DataError2(mappedFromMessageCode, error.message, { tableName, code: embeddedCode, originalError: error });
4654
- }
4655
- }
4656
- const type = classifyByMessage(error.message);
4657
- const fieldName = extractFieldFromError(error.message);
4658
- switch (type) {
4659
- case DataErrorType2.NETWORK_ERROR:
4660
- return createDataError.networkError(error, tableName);
4661
- case DataErrorType2.TIMEOUT_ERROR:
4662
- return createDataError.timeoutError(error, tableName);
4663
- case DataErrorType2.UNAUTHORIZED:
4664
- return createDataError.unauthorized(error.message, tableName);
4665
- case DataErrorType2.FORBIDDEN:
4666
- return createDataError.forbidden(tableName);
4667
- case DataErrorType2.VALIDATION_FAILED:
4668
- return createDataError.validationFailed(tableName, [error.message]);
4669
- case DataErrorType2.UNIQUE_VIOLATION:
4670
- return createDataError.uniqueViolation(error.message, tableName, fieldName);
4671
- case DataErrorType2.FOREIGN_KEY_VIOLATION:
4672
- return createDataError.foreignKeyViolation(error.message, tableName, fieldName);
4673
- case DataErrorType2.NOT_NULL_VIOLATION:
4674
- return createDataError.notNullViolation(error.message, tableName, fieldName);
4675
- case DataErrorType2.CHECK_VIOLATION:
4676
- return createDataError.checkViolation(error.message, tableName, fieldName);
4677
- default:
4678
- return createDataError.unknown(error, tableName);
4679
- }
4680
- }
4681
- const errorMessage = typeof error === "string" ? error : "Unknown error occurred";
4682
- return createDataError.unknown(new Error(errorMessage), tableName);
4683
- }
4684
- function parseError(error) {
4685
- return parseGraphQLError2(error);
4686
- }
4687
- function handleDataError(error, tableName) {
4688
- return error instanceof DataError2 ? error : parseGraphQLError2(error, tableName);
4298
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["NETWORK_ERROR", "TIMEOUT_ERROR", "RATE_LIMITED", "TOO_MANY_REQUESTS"]);
4299
+ function isRetryable(error) {
4300
+ const { code } = parse(error);
4301
+ return Boolean(code && RETRYABLE_CODES.has(code));
4689
4302
  }
4690
4303
  async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4691
4304
  let attempt = 0;
@@ -4693,10 +4306,10 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4693
4306
  try {
4694
4307
  return await fn();
4695
4308
  } catch (error) {
4696
- const dataError = parseGraphQLError2(error);
4309
+ const normalized = toError(error);
4697
4310
  attempt += 1;
4698
- if (!dataError.isRetryable() || attempt >= maxRetries) {
4699
- throw dataError;
4311
+ if (!isRetryable(normalized) || attempt >= maxRetries) {
4312
+ throw normalized;
4700
4313
  }
4701
4314
  if (delayMs > 0) {
4702
4315
  await wait(delayMs);
@@ -4704,9 +4317,18 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3) {
4704
4317
  }
4705
4318
  }
4706
4319
  }
4320
+ var createError2 = {
4321
+ network: (originalError) => errors.NETWORK_ERROR({}, originalError?.message),
4322
+ timeout: () => errors.TIMEOUT_ERROR(),
4323
+ unauthorized: (message = "Authentication required") => errors.UNAUTHENTICATED({}, message),
4324
+ forbidden: (message = "Access forbidden") => errors.FORBIDDEN({}, message),
4325
+ notFound: (message = "Resource not found") => errors.NOT_FOUND({}, message),
4326
+ badRequest: (message) => errors.BAD_USER_INPUT({}, message),
4327
+ graphql: (message, code) => toError(code ? { message, extensions: { code } } : { message }),
4328
+ unknown: (originalError) => toError(originalError)
4329
+ };
4707
4330
  var CONSTRAINT_MESSAGES = {
4708
4331
  // Database provisioning
4709
- // database_schema_hash_key = unique constraint on database name hash, means name conflict
4710
4332
  database_schema_hash_key: "This database name is already taken. Please choose a different name.",
4711
4333
  database_name_key: "This database name is already taken. Please choose a different name.",
4712
4334
  database_provision_module_name_length_min: "Database name must be at least 3 characters.",
@@ -4716,8 +4338,7 @@ var CONSTRAINT_MESSAGES = {
4716
4338
  domain_subdomain_domain_key: "This subdomain is already in use for this domain.",
4717
4339
  // API constraints
4718
4340
  api_name_database_id_key: "An API with this name already exists in this database.",
4719
- // Generic patterns (checked after exact matches)
4720
- // Use * prefix for suffix matching
4341
+ // Generic suffix patterns (checked after exact matches)
4721
4342
  "*_email_key": "This email address is already registered.",
4722
4343
  "*_name_key": "This name is already taken.",
4723
4344
  "*_slug_key": "This URL slug is already in use."
@@ -4728,18 +4349,22 @@ function getConstraintMessage(constraint) {
4728
4349
  return CONSTRAINT_MESSAGES[constraint];
4729
4350
  }
4730
4351
  for (const [pattern, message] of Object.entries(CONSTRAINT_MESSAGES)) {
4731
- if (pattern.startsWith("*")) {
4732
- const suffix = pattern.slice(1);
4733
- if (constraint.endsWith(suffix)) {
4734
- return message;
4735
- }
4352
+ if (pattern.startsWith("*") && constraint.endsWith(pattern.slice(1))) {
4353
+ return message;
4736
4354
  }
4737
4355
  }
4738
4356
  return void 0;
4739
4357
  }
4740
- function getHumanReadableError(error, tableName) {
4741
- const dataError = parseGraphQLError2(error, tableName);
4742
- return dataError.getUserMessage();
4358
+ function parseError(error, locale) {
4359
+ return toError(error, locale);
4360
+ }
4361
+ function parseGraphQLError2(error, locale) {
4362
+ return toError(error, locale);
4363
+ }
4364
+ function getHumanReadableError(error, locale) {
4365
+ const normalized = toError(error, locale);
4366
+ const constraint = typeof normalized.context?.constraint === "string" ? normalized.context.constraint : void 0;
4367
+ return getConstraintMessage(constraint) ?? normalized.message;
4743
4368
  }
4744
4369
 
4745
4370
  // src/mutation-input.ts
@@ -5209,9 +4834,9 @@ var POLICY_PROVISIONING_CONFIG = {
5209
4834
  },
5210
4835
  permission: {
5211
4836
  type: "string",
5212
- component: "permission-select",
5213
- label: "Required Permission",
5214
- description: "Optional permission the user must have"
4837
+ component: "capability-select",
4838
+ label: "Required Capability",
4839
+ description: "Optional capability the user must have"
5215
4840
  },
5216
4841
  is_admin: {
5217
4842
  type: "boolean",
@@ -5245,9 +4870,9 @@ var POLICY_PROVISIONING_CONFIG = {
5245
4870
  fieldOverrides: {
5246
4871
  permission: {
5247
4872
  type: "string",
5248
- component: "permission-select",
5249
- label: "Required Permission",
5250
- description: "Optional permission the user must have"
4873
+ component: "capability-select",
4874
+ label: "Required Capability",
4875
+ description: "Optional capability the user must have"
5251
4876
  },
5252
4877
  is_admin: {
5253
4878
  type: "boolean",
@@ -5412,8 +5037,8 @@ var POLICY_PROVISIONING_CONFIG = {
5412
5037
  },
5413
5038
  permission: {
5414
5039
  type: "string",
5415
- component: "permission-select",
5416
- label: "Required Permission"
5040
+ component: "capability-select",
5041
+ label: "Required Capability"
5417
5042
  },
5418
5043
  is_admin: {
5419
5044
  type: "boolean",
@@ -5709,6 +5334,6 @@ inflection/lib/inflection.js:
5709
5334
  *)
5710
5335
  */
5711
5336
 
5712
- export { CONSTRAINT_MESSAGES, CRUD_OPERATIONS, CRUD_TO_PRIVILEGE, DATA_NODE_GENERATED_FIELDS, DEFAULT_CONSOLE_APPLICATION_SCOPES, DEFAULT_CRUD_GRANT_PRIVILEGES, DataError2 as DataError, DataErrorType2 as DataErrorType, Errors, MEMBERSHIP_TYPES, META_CONTRACT_INTROSPECTION_DOCUMENT, META_CONTRACT_INTROSPECTION_SOURCE, META_CONTRACT_REQUIREMENTS, META_CONTRACT_VERSION, META_DOCUMENT, META_QUERY_SOURCE, MetaContractError, PG_ERROR_CODES2 as PG_ERROR_CODES, POLICY_PROVISIONING_CONFIG, QueryBuilder, SCHEMA_INTROSPECTION_QUERY, TypedDocumentString, analyzeSchemaIntrospectionCompatibility, asFieldIds, assertMetaContract, assertMetaQuery, assessMetaContract, assessSchemaIntrospectionCompatibility, assessTableWriteCapability, buildCount, buildFindOne, buildNodeData, buildNodeDataForDataNodeType, buildPostGraphileCreate, buildPostGraphileDelete, buildPostGraphileUpdate, buildSelect, buildTypeRegistry, cleanTable, cleanTableToMetaObject, convertFromMetaSchema, convertToSelectionOptions, createASTQueryBuilder, createDataError, createError2 as createError, createOne, deleteOne, filterOperations, generateIntrospectionSchema, geometryAst, geometryCollectionAst, geometryPointAst, getAll, getAvailableRelations, getConstraintMessage, getCount, getCustomAst, getCustomAstForCleanField, getCustomOperations, getDataNodeForPolicy, getFieldsRequiringColumns, getGeneratedFields, getHumanReadableError, getMany, getOne, getPolicyCategory, getPolicyFieldDefaults, getPolicyProvisioningConfig, getRowIdentityDefinition, getSelections, getTableOperationNames, groupCrudOperationsByConfig, handleDataError, hasGeneratedFields, injectSchemaFields, intervalAst, isGraphQLVariableValue, isGraphQLVariables, isIntervalType, isRelationalField2 as isRelationalField, isTableOperation, normalizeInflectionValue, normalizeSchemaEnumInputValues, parseError, parseGraphQLError2 as parseGraphQLError, parseGraphQLErrorCode, parseMetaSearchWeights, patchOne, pgFieldToCamelCase, policyCanBeNodeless, policyRequiresDataNode, prepareCreateInput, prepareMutationInput, preparePatchInput, prepareUpdateInput, requiresSubfieldSelection, resolveRowIdentity, rowIdentityToPrimaryKey, sanitizePolicyData, selectConsoleDataTables, serializeRowIdentity, stripEmpty, toCamelCasePlural, toCamelCaseSingular, toCreateInputTypeName, toCreateMutationName, toDeleteInputTypeName, toDeleteMutationName, toFilterTypeName, toOrderByEnumValue, toOrderByTypeName, toPatchFieldName, toUpdateInputTypeName, toUpdateMutationName, transformSchemaToOperations, validateFieldSelection, validateMetaObject, withRetry };
5337
+ export { CONSTRAINT_MESSAGES, CRUD_OPERATIONS, CRUD_TO_PRIVILEGE, DATA_NODE_GENERATED_FIELDS, DEFAULT_CONSOLE_APPLICATION_SCOPES, DEFAULT_CRUD_GRANT_PRIVILEGES, MEMBERSHIP_TYPES, META_CONTRACT_INTROSPECTION_DOCUMENT, META_CONTRACT_INTROSPECTION_SOURCE, META_CONTRACT_REQUIREMENTS, META_CONTRACT_VERSION, META_DOCUMENT, META_QUERY_SOURCE, MetaContractError, POLICY_PROVISIONING_CONFIG, QueryBuilder, SCHEMA_INTROSPECTION_QUERY, TypedDocumentString, analyzeSchemaIntrospectionCompatibility, asFieldIds, assertMetaContract, assertMetaQuery, assessMetaContract, assessSchemaIntrospectionCompatibility, assessTableWriteCapability, buildCount, buildFindOne, buildNodeData, buildNodeDataForDataNodeType, buildPostGraphileCreate, buildPostGraphileDelete, buildPostGraphileUpdate, buildSelect, buildTypeRegistry, cleanTable, cleanTableToMetaObject, convertFromMetaSchema, convertToSelectionOptions, createASTQueryBuilder, createError2 as createError, createOne, deleteOne, filterOperations, generateIntrospectionSchema, geometryAst, geometryCollectionAst, geometryPointAst, getAll, getAvailableRelations, getConstraintMessage, getCount, getCustomAst, getCustomAstForCleanField, getCustomOperations, getDataNodeForPolicy, getErrorCode, getFieldsRequiringColumns, getGeneratedFields, getHumanReadableError, getMany, getOne, getPolicyCategory, getPolicyFieldDefaults, getPolicyProvisioningConfig, getRowIdentityDefinition, getSelections, getTableOperationNames, groupCrudOperationsByConfig, hasGeneratedFields, injectSchemaFields, intervalAst, isAuthenticationError, isGraphQLVariableValue, isGraphQLVariables, isIntervalType, isRelationalField2 as isRelationalField, isRetryable, isTableOperation, normalizeInflectionValue, normalizeSchemaEnumInputValues, parseError, parseGraphQLError2 as parseGraphQLError, parseMetaSearchWeights, patchOne, pgFieldToCamelCase, policyCanBeNodeless, policyRequiresDataNode, prepareCreateInput, prepareMutationInput, preparePatchInput, prepareUpdateInput, requiresSubfieldSelection, resolveRowIdentity, rowIdentityToPrimaryKey, sanitizePolicyData, selectConsoleDataTables, serializeRowIdentity, stripEmpty, toCamelCasePlural, toCamelCaseSingular, toCreateInputTypeName, toCreateMutationName, toDeleteInputTypeName, toDeleteMutationName, toFilterTypeName, toOrderByEnumValue, toOrderByTypeName, toPatchFieldName, toUpdateInputTypeName, toUpdateMutationName, transformSchemaToOperations, validateFieldSelection, validateMetaObject, withRetry };
5713
5338
  //# sourceMappingURL=index.js.map
5714
5339
  //# sourceMappingURL=index.js.map