@lowdefy/errors 0.0.0-experimental-20260928105334 → 0.0.0-experimental-20260928120643

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // Thrown when an authenticated caller is refused by an authorization gate - the
16
+ // caller holds a session or a strategy credential but not the roles the
17
+ // request, endpoint, agent, websocket or auth step requires. Maps to 403. The
18
+ // message is written by the gate and may stay deliberately generic so it does
19
+ // not reveal what exists. The server error handlers branch on the name before
20
+ // the structured-log and Sentry pipeline: a caller with the wrong roles is
21
+ // expected traffic and produces one warning line, not an error log.
22
+ let AuthorizationError = class AuthorizationError extends Error {
23
+ constructor(message = 'Forbidden.', { cause } = {}){
24
+ super(message, {
25
+ cause
26
+ });
27
+ this.name = 'AuthorizationError';
28
+ this.isLowdefyError = true;
29
+ }
30
+ };
31
+ export default AuthorizationError;
@@ -28,8 +28,38 @@
28
28
  'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
29
29
  'DEPTH_ZERO_SELF_SIGNED_CERT'
30
30
  ]);
31
+ // The HTTP status an error carries, in the places client libraries put it: most HTTP
32
+ // clients use `statusCode`, `status` or `response.status`, AWS SDK v3 uses
33
+ // `$metadata.httpStatusCode`, and @google-cloud and SendGrid use a numeric `code`. A
34
+ // numeric `code` outside the HTTP range is a driver's own code (MongoDB), not a status.
35
+ function readHttpStatus(error) {
36
+ if (!error || typeof error !== 'object') return undefined;
37
+ const numericCode = Number.isInteger(error.code) && error.code >= 100 && error.code < 600 ? error.code : undefined;
38
+ return error.statusCode ?? error.status ?? error.response?.status ?? error.$metadata?.httpStatusCode ?? numericCode;
39
+ }
40
+ // The first HTTP status down a retrying client's lastError and the cause chain.
41
+ function findHttpStatus(error, seen = new Set()) {
42
+ if (!error || typeof error !== 'object' || seen.has(error)) return undefined;
43
+ seen.add(error);
44
+ return readHttpStatus(error) ?? findHttpStatus(error.lastError, seen) ?? findHttpStatus(error.cause, seen);
45
+ }
46
+ // 5xx is a failing service; 429 is a service throttling its callers. Both pass with
47
+ // time, and neither is fixed by changing config.
48
+ function isServiceStatus(statusCode) {
49
+ return statusCode === 429 || statusCode >= 500 && statusCode < 600;
50
+ }
51
+ // Retry-After from response headers, which clients expose as a plain object (the AI
52
+ // SDK's responseHeaders, axios and SendGrid response.headers, Stripe headers) or as a
53
+ // fetch Headers instance.
54
+ function readRetryAfterHeader(headers) {
55
+ if (!headers || typeof headers !== 'object') return undefined;
56
+ if (typeof headers.get === 'function') {
57
+ return headers.get('retry-after') ?? undefined;
58
+ }
59
+ return headers['retry-after'] ?? headers['Retry-After'];
60
+ }
31
61
  /**
32
- * Error class for external service failures (network, timeout, database, 5xx).
62
+ * Error class for external service failures (network, timeout, database, 5xx, 429).
33
63
  *
34
64
  * ServiceError represents infrastructure/service issues that are NOT caused by
35
65
  * invalid configuration. The config location is still resolved to help developers
@@ -50,26 +80,43 @@
50
80
  * // error.message = "MongoDB: Connection refused. The service may be down..."
51
81
  */ let ServiceError = class ServiceError extends Error {
52
82
  /**
53
- * Checks if an error is a service error (network issues, timeouts, 5xx).
83
+ * Checks if an error is a service error (network issues, timeouts, 5xx, rate limits).
54
84
  * @param {Error} error - The error to check
85
+ * @param {Set} [seen] - Errors already checked, so a cyclic cause chain ends
55
86
  * @returns {boolean} True if this is a service error
56
- */ static isServiceError(error) {
57
- if (!error) return false;
87
+ */ static isServiceError(error, seen = new Set()) {
88
+ if (!error || seen.has(error)) return false;
89
+ seen.add(error);
90
+ // A client that retried and gave up (the AI SDK's RetryError) carries the
91
+ // failure it retried on; its own message and fields hold no status.
92
+ if (error.lastError) {
93
+ return ServiceError.isServiceError(error.lastError, seen);
94
+ }
58
95
  // Check error code
59
96
  if (error.code && SERVICE_ERROR_CODES.has(error.code)) {
60
97
  return true;
61
98
  }
62
- // Check HTTP status codes (5xx = server error)
63
- const statusCode = error.statusCode ?? error.status ?? error.response?.status;
64
- if (statusCode && statusCode >= 500 && statusCode < 600) {
99
+ // A call cancelled because it ran out of time (AbortSignal.timeout, the AI SDK's
100
+ // timeout option, the server's request timeout).
101
+ if (error.name === 'TimeoutError') {
102
+ return true;
103
+ }
104
+ // AWS SDK v3 marks throttling exceptions as retryable throttling; some services
105
+ // answer them with 400 rather than 429.
106
+ if (error.$retryable?.throttling === true) {
107
+ return true;
108
+ }
109
+ if (isServiceStatus(readHttpStatus(error))) {
65
110
  return true;
66
111
  }
67
112
  // Check for common service error messages
68
113
  const message = error.message?.toLowerCase() ?? '';
69
- if (message.includes('network') || message.includes('timeout') || message.includes('connection refused') || message.includes('dns lookup failed') || message.includes('socket hang up') || message.includes('certificate') || message.includes('unavailable')) {
114
+ if (message.includes('network') || message.includes('timeout') || message.includes('too many requests') || message.includes('connection refused') || message.includes('dns lookup failed') || message.includes('socket hang up') || message.includes('certificate') || message.includes('unavailable')) {
70
115
  return true;
71
116
  }
72
- return false;
117
+ // A client error that wraps the network failure underneath it (the AI
118
+ // SDK's "Cannot connect to API" around a refused or timed-out fetch).
119
+ return ServiceError.isServiceError(error.cause, seen);
73
120
  }
74
121
  /**
75
122
  * Enhances an error message with more helpful context.
@@ -77,7 +124,7 @@
77
124
  * @returns {string} Enhanced error message
78
125
  */ static enhanceMessage(error) {
79
126
  const code = error.code;
80
- const statusCode = error.statusCode ?? error.status ?? error.response?.status;
127
+ const statusCode = findHttpStatus(error);
81
128
  if (code === 'ECONNREFUSED') {
82
129
  return `Connection refused. The service may be down or the address may be incorrect. ${error.message ?? ''}`;
83
130
  }
@@ -90,12 +137,32 @@
90
137
  if (code === 'ECONNRESET') {
91
138
  return `Connection reset by the server. ${error.message ?? ''}`;
92
139
  }
140
+ if (statusCode === 429) {
141
+ const retryAfter = ServiceError.readRetryAfter(error);
142
+ const retry = retryAfter ? ` Retry after ${retryAfter}.` : '';
143
+ return `Rate limited by the service (429 Too Many Requests).${retry} ${error.message ?? ''}`;
144
+ }
93
145
  if (statusCode && statusCode >= 500) {
94
146
  return `Server returned error ${statusCode}. ${error.message ?? ''}`;
95
147
  }
96
148
  return error.message;
97
149
  }
98
150
  /**
151
+ * Reads the Retry-After header a throttling service sent, from the error, the
152
+ * failure a retrying client gave up on, or its cause chain.
153
+ * @param {Error} error - The error to read
154
+ * @param {Set} [seen] - Errors already read, so a cyclic cause chain ends
155
+ * @returns {string|null} The header value (seconds or an HTTP date), or null
156
+ */ static readRetryAfter(error, seen = new Set()) {
157
+ if (!error || typeof error !== 'object' || seen.has(error)) return null;
158
+ seen.add(error);
159
+ const retryAfter = readRetryAfterHeader(error.responseHeaders) ?? readRetryAfterHeader(error.response?.headers) ?? readRetryAfterHeader(error.headers) ?? readRetryAfterHeader(error.$response?.headers);
160
+ if (retryAfter !== undefined && retryAfter !== null) {
161
+ return String(retryAfter);
162
+ }
163
+ return ServiceError.readRetryAfter(error.lastError, seen) ?? ServiceError.readRetryAfter(error.cause, seen);
164
+ }
165
+ /**
99
166
  * Creates a ServiceError instance with formatted message.
100
167
  * @param {string} [message] - Error message (falls back to enhanced cause message)
101
168
  * @param {Object} [options]
@@ -104,10 +171,14 @@
104
171
  * @param {string} [options.code] - Error code (e.g., 'ECONNREFUSED')
105
172
  * @param {number} [options.statusCode] - HTTP status code if applicable
106
173
  * @param {string} [options.configKey] - Config key for location resolution
107
- */ constructor(message, { cause, service, code, statusCode, configKey } = {}){
174
+ * @param {string} [options.hint] - A sentence telling the developer what to do about the
175
+ * failure. Enumerable, so it survives serialization to the client.
176
+ * @param {string} [options.retryAfter] - The Retry-After a throttling service sent
177
+ * (seconds or an HTTP date). Read from the cause when not given.
178
+ */ constructor(message, { cause, service, code, statusCode, configKey, hint, retryAfter } = {}){
108
179
  // Extract info from wrapped error if provided
109
180
  const errorCode = code ?? cause?.code;
110
- const errorStatusCode = statusCode ?? cause?.statusCode ?? cause?.status ?? cause?.response?.status;
181
+ const errorStatusCode = statusCode ?? findHttpStatus(cause);
111
182
  // Use provided message, or enhance wrapped error's message
112
183
  const baseMessage = message ?? (cause ? ServiceError.enhanceMessage(cause) : 'Service error');
113
184
  // Message without prefix - logger uses error.name for display
@@ -121,8 +192,12 @@
121
192
  this._message = baseMessage;
122
193
  this.service = service;
123
194
  this.code = errorCode;
195
+ this.hint = hint ?? cause?.hint ?? null;
124
196
  this.statusCode = errorStatusCode;
125
- this.configKey = configKey ?? null;
197
+ this.retryAfter = retryAfter ?? ServiceError.readRetryAfter(cause);
198
+ // Extract from the wrapped error like PluginError does, so a ServiceError
199
+ // wrapped around an error that already resolved its config location keeps it.
200
+ this.configKey = configKey ?? cause?.configKey ?? null;
126
201
  }
127
202
  };
128
203
  export default ServiceError;
@@ -0,0 +1,31 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // Thrown when an authorized caller has not enrolled a second factor and the
16
+ // deployment sets auth.twoFactor.required. Distinct from AuthenticationError on
17
+ // purpose: a 401 reads to the client as a dead session and bounces the user to
18
+ // sign-in, which is the redirect loop the enrolment gate exists to avoid, so this
19
+ // maps to 403. The server error handlers branch on the name before the
20
+ // structured-log and Sentry pipeline - under required: true this is expected
21
+ // traffic from every unenrolled caller, not a fault.
22
+ let TwoFactorEnrolmentRequiredError = class TwoFactorEnrolmentRequiredError extends Error {
23
+ constructor(message = 'Two-factor enrolment required.', { cause } = {}){
24
+ super(message, {
25
+ cause
26
+ });
27
+ this.name = 'TwoFactorEnrolmentRequiredError';
28
+ this.isLowdefyError = true;
29
+ }
30
+ };
31
+ export default TwoFactorEnrolmentRequiredError;
@@ -16,7 +16,10 @@
16
16
  if (typeof error === 'string') return error;
17
17
  if (error?.message === undefined) return String(error);
18
18
  const name = error.name || 'Error';
19
- let msg = `[${name}] ${error.message}`;
19
+ // Prod-gated build warnings are not fatal in dev but fail `lowdefy build`, so
20
+ // the name segment says so wherever the error is displayed.
21
+ const nameSegment = error.prodError === true ? `${name} · fails in prod` : name;
22
+ let msg = `[${nameSegment}] ${error.message}`;
20
23
  if (error.received !== undefined) {
21
24
  try {
22
25
  msg = `${msg} Received: ${JSON.stringify(error.received)}`;
package/dist/index.js CHANGED
@@ -42,9 +42,13 @@
42
42
  * - Extends ConfigError with name override
43
43
  * - Format: source:line\n[ConfigWarning] message
44
44
  *
45
- * 6. UserError - User-authored deliberate failure
46
- * - Thrown: Client-side Throw action; server-side controlThrow (routine :throw) and controlReject (routine :reject)
47
- * - Caught: Caller of the action/resolver; signals "the called routine deliberately failed" as distinct from a system fault
45
+ * 6. UserError - An expected outcome of user interaction, never a config or system fault
46
+ * - Thrown: Client-side Throw and Validate actions; server-side controlThrow (routine :throw)
47
+ * and controlReject (routine :reject); client auth methods when the auth server rejects
48
+ * the attempt (4xx: wrong password, expired or used link, invalid code, stale OAuth query)
49
+ * - Caught: Caller of the action/resolver; the message is shown to the user and catch actions
50
+ * run, but it logs to the browser console only - never posted to /api/client-error, never
51
+ * logged on the server at error level, never resolved to a config location
48
52
  * - Format: [User Error] message
49
53
  *
50
54
  * 7. AuthenticationError - Unauthenticated request to a protected endpoint
@@ -52,6 +56,16 @@
52
56
  * - Caught: Server error handlers, before structured logging and Sentry (401)
53
57
  * - Format: [AuthenticationError] message
54
58
  *
59
+ * 8. TwoFactorEnrolmentRequiredError - Authorized caller with no enrolled second factor
60
+ * - Thrown: The authorization gate, when auth.twoFactor.required is set and the caller is unenrolled
61
+ * - Caught: Server error handlers, before structured logging and Sentry (403)
62
+ * - Format: [TwoFactorEnrolmentRequiredError] message
63
+ *
64
+ * 9. AuthorizationError - Authenticated caller refused by an authorization gate (wrong roles)
65
+ * - Thrown: Request, endpoint, agent, websocket and auth-step authorization gates
66
+ * - Caught: Server error handlers, before structured logging and Sentry (403)
67
+ * - Format: [AuthorizationError] message
68
+ *
55
69
  * Location Resolution Utilities:
56
70
  * resolveConfigLocation - Sync: configKey → {source, config} via keyMap/refMap
57
71
  * resolveErrorLocation - Sync: unified resolver (configKey or filePath/lineNumber)
@@ -64,6 +78,7 @@
64
78
  * lowdefyErrorTypes - Lowdefy error class by name, for reviving and reshaping errors
65
79
  */ import ActionError from './ActionError.js';
66
80
  import AuthenticationError from './AuthenticationError.js';
81
+ import AuthorizationError from './AuthorizationError.js';
67
82
  import BlockError from './BlockError.js';
68
83
  import BuildError from './BuildError.js';
69
84
  import ConfigError from './ConfigError.js';
@@ -81,5 +96,6 @@ import loadAndResolveErrorLocation from './loadAndResolveErrorLocation.js';
81
96
  import resolveErrorLocation from './resolveErrorLocation.js';
82
97
  import ServiceError from './ServiceError.js';
83
98
  import shouldSuppressBuildCheck, { VALID_CHECK_SLUGS } from './shouldSuppressBuildCheck.js';
99
+ import TwoFactorEnrolmentRequiredError from './TwoFactorEnrolmentRequiredError.js';
84
100
  import UserError from './UserError.js';
85
- export { ActionError, AuthenticationError, BlockError, BuildError, ConfigError, ConfigWarning, errorToDisplayString, LowdefyInternalError, lowdefyErrorNames, lowdefyErrorTypes, OperatorError, PluginError, readErrorCodes, RequestError, resolveConfigLocation, loadAndResolveErrorLocation, resolveErrorLocation, ServiceError, shouldSuppressBuildCheck, UserError, VALID_CHECK_SLUGS };
101
+ export { ActionError, AuthenticationError, AuthorizationError, BlockError, BuildError, ConfigError, ConfigWarning, errorToDisplayString, LowdefyInternalError, lowdefyErrorNames, lowdefyErrorTypes, OperatorError, PluginError, readErrorCodes, RequestError, resolveConfigLocation, loadAndResolveErrorLocation, resolveErrorLocation, ServiceError, shouldSuppressBuildCheck, TwoFactorEnrolmentRequiredError, UserError, VALID_CHECK_SLUGS };
@@ -13,6 +13,8 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import ActionError from './ActionError.js';
16
+ import AuthenticationError from './AuthenticationError.js';
17
+ import AuthorizationError from './AuthorizationError.js';
16
18
  import BlockError from './BlockError.js';
17
19
  import BuildError from './BuildError.js';
18
20
  import ConfigError from './ConfigError.js';
@@ -22,11 +24,14 @@ import OperatorError from './OperatorError.js';
22
24
  import PluginError from './PluginError.js';
23
25
  import RequestError from './RequestError.js';
24
26
  import ServiceError from './ServiceError.js';
27
+ import TwoFactorEnrolmentRequiredError from './TwoFactorEnrolmentRequiredError.js';
25
28
  import UserError from './UserError.js';
26
29
  // Name to class, for rebuilding an error whose class identity is gone but whose
27
30
  // name survived - a serializer round trip, or a caught error being reshaped.
28
31
  const lowdefyErrorTypes = {
29
32
  ActionError,
33
+ AuthenticationError,
34
+ AuthorizationError,
30
35
  BlockError,
31
36
  BuildError,
32
37
  ConfigError,
@@ -36,6 +41,7 @@ const lowdefyErrorTypes = {
36
41
  PluginError,
37
42
  RequestError,
38
43
  ServiceError,
44
+ TwoFactorEnrolmentRequiredError,
39
45
  UserError
40
46
  };
41
47
  export default lowdefyErrorTypes;
@@ -23,8 +23,14 @@
23
23
  'link-refs': 'Invalid Link action page reference warnings',
24
24
  'request-refs': 'Invalid Request action reference warnings',
25
25
  'connection-refs': 'Nonexistent connection ID references',
26
+ 'callapi-refs': 'Invalid CallAPI action endpoint reference warnings',
27
+ 'callapi-internal-refs': 'CallAPI actions targeting InternalApi endpoints',
28
+ 'dynamic-endpoint-refs': 'Invalid Dynamic block endpoint reference warnings',
29
+ 'websocket-refs': 'Invalid websocket action reference warnings',
30
+ icons: 'Unresolvable icon name warnings',
26
31
  types: 'All type validation (blocks, operators, actions, requests, connections)',
27
- schema: 'JSON schema validation errors'
32
+ schema: 'JSON schema validation errors',
33
+ secrets: 'Environment variable names that are not set in the build environment'
28
34
  };
29
35
  /**
30
36
  * Checks if a build check should be suppressed based on ~ignoreBuildChecks.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/errors",
3
- "version": "0.0.0-experimental-20260928105334",
3
+ "version": "0.0.0-experimental-20260928120643",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Lowdefy error classes for consistent error handling across build, server, and client",
6
6
  "homepage": "https://lowdefy.com",