@svadmin/core 0.71.0 → 0.73.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.
@@ -0,0 +1,418 @@
1
+ import { HttpError, UndoError, type ValidationErrors, type HttpErrorOptions } from './types';
2
+ import { definedOptions } from './defined-options';
3
+
4
+ export class ValidationError extends HttpError {
5
+ readonly _tag = 'ValidationError' as const;
6
+ readonly fieldErrors: ValidationErrors;
7
+
8
+ constructor(
9
+ message: string = 'Validation failed',
10
+ fieldErrors: ValidationErrors = {},
11
+ options: HttpErrorOptions = {},
12
+ ) {
13
+ super(message, 422, fieldErrors, definedOptions({
14
+ code: options.code ?? 'VALIDATION_FAILED',
15
+ details: options.details,
16
+ body: options.body,
17
+ cause: options.cause,
18
+ }));
19
+ this.name = 'ValidationError';
20
+ this.fieldErrors = fieldErrors;
21
+ }
22
+ }
23
+
24
+ export interface ConflictErrorOptions extends HttpErrorOptions {
25
+ resource?: string | undefined;
26
+ recordId?: string | number | undefined;
27
+ currentVersion?: string | number | undefined;
28
+ expectedVersion?: string | number | undefined;
29
+ }
30
+
31
+ export class ConflictError extends HttpError {
32
+ readonly _tag = 'ConflictError' as const;
33
+ readonly resource?: string | undefined;
34
+ readonly recordId?: string | number | undefined;
35
+ readonly currentVersion?: string | number | undefined;
36
+ readonly expectedVersion?: string | number | undefined;
37
+
38
+ constructor(
39
+ message: string = 'Resource conflict detected',
40
+ options: ConflictErrorOptions = {},
41
+ ) {
42
+ super(message, 409, undefined, definedOptions({
43
+ code: options.code ?? 'RESOURCE_CONFLICT',
44
+ details: options.details,
45
+ body: options.body,
46
+ cause: options.cause,
47
+ }));
48
+ this.name = 'ConflictError';
49
+ this.resource = options.resource;
50
+ this.recordId = options.recordId;
51
+ this.currentVersion = options.currentVersion;
52
+ this.expectedVersion = options.expectedVersion;
53
+ }
54
+ }
55
+
56
+ export interface AuthErrorOptions extends HttpErrorOptions {
57
+ resource?: string | undefined;
58
+ action?: string | undefined;
59
+ }
60
+
61
+ export class AuthError extends HttpError {
62
+ readonly _tag = 'AuthError' as const;
63
+ readonly kind: 'unauthorized' | 'forbidden';
64
+ readonly resource?: string | undefined;
65
+ readonly action?: string | undefined;
66
+
67
+ constructor(
68
+ kind: 'unauthorized' | 'forbidden',
69
+ message?: string,
70
+ options: AuthErrorOptions = {},
71
+ ) {
72
+ const statusCode = kind === 'unauthorized' ? 401 : 403;
73
+ const defaultMsg = kind === 'unauthorized' ? 'Authentication required' : 'Permission denied';
74
+ super(message ?? defaultMsg, statusCode, undefined, definedOptions({
75
+ code: options.code ?? (kind === 'unauthorized' ? 'UNAUTHORIZED' : 'FORBIDDEN'),
76
+ details: options.details,
77
+ body: options.body,
78
+ cause: options.cause,
79
+ }));
80
+ this.name = 'AuthError';
81
+ this.kind = kind;
82
+ this.resource = options.resource;
83
+ this.action = options.action;
84
+ }
85
+ }
86
+
87
+ export interface NetworkErrorOptions extends HttpErrorOptions {
88
+ isTimeout?: boolean | undefined;
89
+ isOffline?: boolean | undefined;
90
+ statusCode?: number | undefined;
91
+ }
92
+
93
+ export class NetworkError extends HttpError {
94
+ readonly _tag = 'NetworkError' as const;
95
+ readonly isTimeout: boolean;
96
+ readonly isOffline: boolean;
97
+ readonly retryable = true as const;
98
+
99
+ constructor(
100
+ message: string = 'Network communication failure',
101
+ options: NetworkErrorOptions = {},
102
+ ) {
103
+ const isTimeout = options.isTimeout ?? false;
104
+ super(message, options.statusCode ?? (isTimeout ? 504 : 0), undefined, definedOptions({
105
+ code: options.code ?? (isTimeout ? 'NETWORK_TIMEOUT' : 'NETWORK_ERROR'),
106
+ details: options.details,
107
+ body: options.body,
108
+ cause: options.cause,
109
+ }));
110
+ this.name = 'NetworkError';
111
+ this.isTimeout = isTimeout;
112
+ this.isOffline = options.isOffline ?? false;
113
+ }
114
+ }
115
+
116
+ export interface ContractDecodingErrorOptions extends HttpErrorOptions {
117
+ resource?: string | undefined;
118
+ issues?: readonly unknown[] | undefined;
119
+ }
120
+
121
+ export class ContractDecodingError extends HttpError {
122
+ readonly _tag = 'ContractDecodingError' as const;
123
+ readonly resource?: string | undefined;
124
+ readonly issues?: readonly unknown[] | undefined;
125
+
126
+ constructor(
127
+ message: string = 'Contract decoding mismatch',
128
+ options: ContractDecodingErrorOptions = {},
129
+ ) {
130
+ super(message, 502, undefined, definedOptions({
131
+ code: options.code ?? 'CONTRACT_DECODING_ERROR',
132
+ details: options.details ?? options.issues,
133
+ body: options.body,
134
+ cause: options.cause,
135
+ }));
136
+ this.name = 'ContractDecodingError';
137
+ this.resource = options.resource;
138
+ this.issues = options.issues;
139
+ }
140
+ }
141
+
142
+ export interface NotFoundErrorOptions extends HttpErrorOptions {
143
+ resource?: string | undefined;
144
+ id?: string | number | undefined;
145
+ }
146
+
147
+ export class NotFoundError extends HttpError {
148
+ readonly _tag = 'NotFoundError' as const;
149
+ readonly resource?: string | undefined;
150
+ readonly id?: string | number | undefined;
151
+
152
+ constructor(
153
+ message: string = 'Resource not found',
154
+ options: NotFoundErrorOptions = {},
155
+ ) {
156
+ super(message, 404, undefined, definedOptions({
157
+ code: options.code ?? 'RESOURCE_NOT_FOUND',
158
+ details: options.details,
159
+ body: options.body,
160
+ cause: options.cause,
161
+ }));
162
+ this.name = 'NotFoundError';
163
+ this.resource = options.resource;
164
+ this.id = options.id;
165
+ }
166
+ }
167
+
168
+ export interface ServerInternalErrorOptions extends HttpErrorOptions {
169
+ traceId?: string | undefined;
170
+ }
171
+
172
+ export class ServerInternalError extends HttpError {
173
+ readonly _tag = 'ServerInternalError' as const;
174
+ readonly traceId?: string | undefined;
175
+
176
+ constructor(
177
+ message: string = 'Internal server failure',
178
+ statusCode: number = 500,
179
+ options: ServerInternalErrorOptions = {},
180
+ ) {
181
+ super(message, statusCode, undefined, definedOptions({
182
+ code: options.code ?? 'INTERNAL_SERVER_ERROR',
183
+ details: options.details,
184
+ body: options.body,
185
+ cause: options.cause,
186
+ }));
187
+ this.name = 'ServerInternalError';
188
+ this.traceId = options.traceId;
189
+ }
190
+ }
191
+
192
+ export class BadRequestError extends HttpError {
193
+ readonly _tag = 'BadRequestError' as const;
194
+ readonly fieldErrors: ValidationErrors;
195
+
196
+ constructor(
197
+ message: string = 'Bad request',
198
+ fieldErrors: ValidationErrors = {},
199
+ options: HttpErrorOptions = {},
200
+ ) {
201
+ super(message, 400, fieldErrors, definedOptions({
202
+ code: options.code ?? 'BAD_REQUEST',
203
+ details: options.details,
204
+ body: options.body,
205
+ cause: options.cause,
206
+ }));
207
+ this.name = 'BadRequestError';
208
+ this.fieldErrors = fieldErrors;
209
+ }
210
+ }
211
+
212
+ export class RateLimitError extends HttpError {
213
+ readonly _tag = 'RateLimitError' as const;
214
+ readonly retryable = true as const;
215
+
216
+ constructor(
217
+ message: string = 'Rate limit exceeded',
218
+ options: HttpErrorOptions = {},
219
+ ) {
220
+ super(message, 429, undefined, definedOptions({
221
+ code: options.code ?? 'RATE_LIMITED',
222
+ details: options.details,
223
+ body: options.body,
224
+ cause: options.cause,
225
+ }));
226
+ this.name = 'RateLimitError';
227
+ }
228
+ }
229
+
230
+ export class UnavailableError extends HttpError {
231
+ readonly _tag = 'UnavailableError' as const;
232
+ readonly retryable = true as const;
233
+
234
+ constructor(
235
+ message: string = 'Service unavailable',
236
+ statusCode: number = 503,
237
+ options: HttpErrorOptions = {},
238
+ ) {
239
+ super(message, statusCode, undefined, definedOptions({
240
+ code: options.code ?? 'SERVICE_UNAVAILABLE',
241
+ details: options.details,
242
+ body: options.body,
243
+ cause: options.cause,
244
+ }));
245
+ this.name = 'UnavailableError';
246
+ }
247
+ }
248
+
249
+ export class CancelledError extends HttpError {
250
+ readonly _tag = 'CancelledError' as const;
251
+ readonly writeMayHaveSucceeded: boolean;
252
+
253
+ constructor(
254
+ message: string = 'Operation cancelled',
255
+ statusCode: number = 409,
256
+ options: HttpErrorOptions = {},
257
+ ) {
258
+ super(message, statusCode, undefined, definedOptions({
259
+ code: options.code ?? 'OPERATION_CANCELLED',
260
+ details: options.details,
261
+ body: options.body,
262
+ cause: options.cause,
263
+ }));
264
+ this.name = 'CancelledError';
265
+ this.writeMayHaveSucceeded = writeMayHaveSucceeded(options.details);
266
+ }
267
+ }
268
+
269
+ export class AbortedError extends HttpError {
270
+ readonly _tag = 'AbortedError' as const;
271
+ readonly retryable = false as const;
272
+
273
+ constructor(
274
+ message: string = 'Operation aborted',
275
+ options: HttpErrorOptions = {},
276
+ ) {
277
+ super(message, 0, undefined, definedOptions({
278
+ code: options.code ?? 'ABORTED',
279
+ details: options.details,
280
+ body: options.body,
281
+ cause: options.cause,
282
+ }));
283
+ this.name = 'AbortedError';
284
+ }
285
+ }
286
+
287
+ /** 用户撤销不是服务器失败,不能伪装成 500。 */
288
+ export class UndoneError extends Error {
289
+ readonly _tag = 'UndoneError' as const;
290
+
291
+ constructor(
292
+ message: string = 'Mutation undone',
293
+ options: { cause?: unknown } = {},
294
+ ) {
295
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
296
+ this.name = 'UndoneError';
297
+ }
298
+ }
299
+
300
+ export type DomainError =
301
+ | ValidationError
302
+ | ConflictError
303
+ | AuthError
304
+ | NetworkError
305
+ | ContractDecodingError
306
+ | NotFoundError
307
+ | ServerInternalError
308
+ | BadRequestError
309
+ | RateLimitError
310
+ | UnavailableError
311
+ | CancelledError
312
+ | AbortedError
313
+ | UndoneError;
314
+
315
+ export type DomainErrorTag = DomainError['_tag'];
316
+
317
+ type ErrorHandlers<E extends { readonly _tag: string }, R> = {
318
+ [K in E['_tag']]: (error: Extract<E, { readonly _tag: K }>) => R;
319
+ };
320
+
321
+ /** 要么覆盖全部分支,要么提供 `_` 兜底。缺分支在编译期失败。 */
322
+ export type ErrorPattern<E extends { readonly _tag: string }, R> =
323
+ | ErrorHandlers<E, R>
324
+ | (Partial<ErrorHandlers<E, R>> & { _: (error: E) => R });
325
+
326
+ export function matchError<E extends { readonly _tag: string }, R>(
327
+ error: E,
328
+ patterns: ErrorPattern<E, R>,
329
+ ): R {
330
+ const tag = error._tag as E['_tag'];
331
+ const handler = (patterns as Partial<ErrorHandlers<E, R>>)[tag];
332
+ if (typeof handler === 'function') {
333
+ return handler(error as never);
334
+ }
335
+ if ('_' in patterns && typeof patterns._ === 'function') {
336
+ return patterns._(error);
337
+ }
338
+ throw new Error(`Unhandled domain error tag: ${tag}`);
339
+ }
340
+
341
+ function writeMayHaveSucceeded(details: unknown): boolean {
342
+ return typeof details === 'object'
343
+ && details !== null
344
+ && 'writeMayHaveSucceeded' in details
345
+ && details.writeMayHaveSucceeded === true;
346
+ }
347
+
348
+ function carried(cause: HttpError): HttpErrorOptions {
349
+ return definedOptions({
350
+ code: cause.code,
351
+ details: cause.details,
352
+ body: cause.body,
353
+ cause,
354
+ });
355
+ }
356
+
357
+ function isDomainError(cause: unknown): cause is DomainError {
358
+ return cause instanceof ValidationError
359
+ || cause instanceof ConflictError
360
+ || cause instanceof AuthError
361
+ || cause instanceof NetworkError
362
+ || cause instanceof ContractDecodingError
363
+ || cause instanceof NotFoundError
364
+ || cause instanceof ServerInternalError
365
+ || cause instanceof BadRequestError
366
+ || cause instanceof RateLimitError
367
+ || cause instanceof UnavailableError
368
+ || cause instanceof CancelledError
369
+ || cause instanceof AbortedError
370
+ || cause instanceof UndoneError;
371
+ }
372
+
373
+ /**
374
+ * 保留 HttpError 的 code、details、body。
375
+ * 取消和撤销不能改写成冲突或 500,否则 safeMutate 会丢掉 writeMayHaveSucceeded。
376
+ */
377
+ export function toDomainError(cause: unknown): DomainError {
378
+ if (isDomainError(cause)) return cause;
379
+
380
+ if (cause instanceof UndoError) {
381
+ return new UndoneError(cause.message, { cause });
382
+ }
383
+
384
+ if (cause instanceof HttpError) {
385
+ const options = carried(cause);
386
+ if (typeof cause.code === 'string' && cause.code.endsWith('_CANCELLED')) {
387
+ return new CancelledError(cause.message, cause.statusCode, options);
388
+ }
389
+ const status = cause.statusCode;
390
+ if (status === 422) return new ValidationError(cause.message, cause.errors ?? {}, options);
391
+ if (status === 409) return new ConflictError(cause.message, options);
392
+ if (status === 401) return new AuthError('unauthorized', cause.message, options);
393
+ if (status === 403) return new AuthError('forbidden', cause.message, options);
394
+ if (status === 404) return new NotFoundError(cause.message, options);
395
+ if (status === 400) return new BadRequestError(cause.message, cause.errors ?? {}, options);
396
+ if (status === 408 || status === 504 || status === 0) {
397
+ return new NetworkError(cause.message, definedOptions({
398
+ isTimeout: status === 408 || status === 504,
399
+ statusCode: status,
400
+ code: cause.code,
401
+ details: cause.details,
402
+ body: cause.body,
403
+ cause,
404
+ }));
405
+ }
406
+ if (status === 429) return new RateLimitError(cause.message, options);
407
+ if (status === 503) return new UnavailableError(cause.message, status, options);
408
+ return new ServerInternalError(cause.message, status, options);
409
+ }
410
+
411
+ if (cause instanceof Error) {
412
+ if (cause.name === 'AbortError') return new AbortedError(cause.message, { cause });
413
+ if (cause.name === 'TimeoutError') return new NetworkError(cause.message, { isTimeout: true, cause });
414
+ return new ServerInternalError(cause.message, 500, { cause });
415
+ }
416
+
417
+ return new ServerInternalError(typeof cause === 'string' ? cause : 'Unknown system error', 500, { cause });
418
+ }
package/src/index.ts CHANGED
@@ -215,8 +215,10 @@ export type {
215
215
  MessageStatus, ToolState, AgentProvider, AgentEvent, AgentOptions, ApprovalResponseOptions,
216
216
  AdminTool, ToolResult,
217
217
  } from './chatProvider.svelte';
218
- export { getTheme, setTheme, toggleTheme, getResolvedTheme, getColorTheme, setColorTheme, getColorThemes, configureTheme, getThemeConfig, clearCssOverrides, builtinPresets, registerColorPreset, getColorPresets, registerThemeOwner, updateThemeOwner, unregisterThemeOwner, resetTheme } from './theme.svelte';
219
- export type { ThemeMode, ColorTheme, ThemeStrategy, ThemeConfig, ColorPreset, ThemeOwnerOptions, ThemeOwnerToken } from './theme.svelte';
218
+ export { getTheme, setTheme, toggleTheme, getResolvedTheme, getColorTheme, setColorTheme, getColorThemes, configureTheme, getThemeConfig, clearCssOverrides, builtinPresets, registerColorPreset, getColorPresets, registerColorTheme, exportColorThemes, importColorThemes, registerThemeOwner, updateThemeOwner, unregisterThemeOwner, resetTheme } from './theme.svelte';
219
+ export { deriveColorPreset, exportThemeTokens, generateColorScale, hexToOklch, parseThemeTokens, pickReadableForeground } from './color-scale';
220
+ export type { ColorScaleStep, DerivedColorPreset, ThemeTokenDocument } from './color-scale';
221
+ export type { ThemeMode, ColorTheme, BuiltinColorTheme, ThemeStrategy, ThemeConfig, ColorPreset, ThemeOwnerOptions, ThemeOwnerToken } from './theme.svelte';
220
222
  export { setUnsavedChanges, getUnsavedChanges, initUnsavedChangesNotifier, resetUnsavedChanges } from './unsaved-changes.svelte';
221
223
  export { setAdminOptions, getAdminOptions, getTextTransformers } from './options.svelte';
222
224
  export type { AdminOptions, TextTransformers, OvertimeConfig } from './options.svelte';
@@ -423,3 +425,52 @@ export { formatProductPreview, runProductPipeline } from './product-pipeline';
423
425
  export type { ProductPipelineInput, ProductPipelineOutput } from './product-pipeline';
424
426
  export { reviewProductPlan } from './product-review';
425
427
  export type { ProductReviewIssue, ProductReviewMetrics, ProductReviewReport, ProductReviewSeverity } from './product-review';
428
+
429
+ // High-Rigor Typed Result, Domain Errors & Resilience
430
+ export {
431
+ ok, err, isOk, isErr, unwrapResult, unwrapOr,
432
+ mapResult, mapErr, flatMapResult, matchResult,
433
+ fromThrowable, fromPromise,
434
+ } from './result';
435
+ export type { Result, Ok, Err } from './result';
436
+
437
+ export {
438
+ ValidationError,
439
+ ConflictError,
440
+ AuthError,
441
+ NetworkError,
442
+ ContractDecodingError,
443
+ NotFoundError,
444
+ ServerInternalError,
445
+ BadRequestError,
446
+ RateLimitError,
447
+ UnavailableError,
448
+ CancelledError,
449
+ AbortedError,
450
+ UndoneError,
451
+ matchError,
452
+ toDomainError,
453
+ } from './domain-errors';
454
+ export type {
455
+ DomainError,
456
+ DomainErrorTag,
457
+ ErrorPattern,
458
+ ConflictErrorOptions,
459
+ AuthErrorOptions,
460
+ NetworkErrorOptions,
461
+ ContractDecodingErrorOptions,
462
+ NotFoundErrorOptions,
463
+ ServerInternalErrorOptions,
464
+ } from './domain-errors';
465
+
466
+ export {
467
+ ConcurrencyLimitClearedError,
468
+ createConcurrencyLimiter,
469
+ withRetry,
470
+ wrapDataProviderWithResult,
471
+ } from './resilience';
472
+ export type {
473
+ ConcurrencyLimiter,
474
+ RetryOptions,
475
+ SafeDataProvider,
476
+ } from './resilience';
@@ -0,0 +1,185 @@
1
+ import { err, fromPromise, type Result } from './result';
2
+ import { toDomainError, type DomainError } from './domain-errors';
3
+ import type {
4
+ DataProvider,
5
+ GetListParams,
6
+ GetListResult,
7
+ GetOneParams,
8
+ GetOneResult,
9
+ CreateParams,
10
+ CreateResult,
11
+ UpdateParams,
12
+ UpdateResult,
13
+ DeleteParams,
14
+ DeleteResult,
15
+ GetManyParams,
16
+ GetManyResult,
17
+ CreateManyParams,
18
+ CreateManyResult,
19
+ UpdateManyParams,
20
+ UpdateManyResult,
21
+ DeleteManyParams,
22
+ DeleteManyResult,
23
+ CustomParams,
24
+ CustomResult,
25
+ } from './types';
26
+
27
+ export class ConcurrencyLimitClearedError extends Error {
28
+ constructor() {
29
+ super('Concurrency limiter cleared');
30
+ this.name = 'ConcurrencyLimitClearedError';
31
+ }
32
+ }
33
+
34
+ export interface ConcurrencyLimiter {
35
+ <T>(fn: () => Promise<T>): Promise<T>;
36
+ readonly activeCount: number;
37
+ readonly pendingCount: number;
38
+ clear(): void;
39
+ }
40
+
41
+ interface LimitWaiter {
42
+ resolve: () => void;
43
+ reject: (error: unknown) => void;
44
+ }
45
+
46
+ /**
47
+ * Creates a lightweight concurrency limiter (zero external dependencies).
48
+ * Perfect for batch imports, multi-record deletions, and asset uploads.
49
+ */
50
+ export function createConcurrencyLimiter(concurrency: number): ConcurrencyLimiter {
51
+ if (concurrency < 1) {
52
+ throw new RangeError('Concurrency limit must be at least 1');
53
+ }
54
+
55
+ let active = 0;
56
+ const queue: LimitWaiter[] = [];
57
+
58
+ const next = () => {
59
+ if (active < concurrency && queue.length > 0) {
60
+ const run = queue.shift();
61
+ if (run) {
62
+ active++;
63
+ run.resolve();
64
+ }
65
+ }
66
+ };
67
+
68
+ const limiter = async <T>(fn: () => Promise<T>): Promise<T> => {
69
+ await new Promise<void>((resolve, reject) => {
70
+ queue.push({ resolve, reject });
71
+ next();
72
+ });
73
+
74
+ try {
75
+ return await fn();
76
+ } finally {
77
+ active--;
78
+ next();
79
+ }
80
+ };
81
+
82
+ Object.defineProperties(limiter, {
83
+ activeCount: { get: () => active },
84
+ pendingCount: { get: () => queue.length },
85
+ });
86
+
87
+ limiter.clear = () => {
88
+ const dropped = queue.splice(0);
89
+ for (const waiter of dropped) waiter.reject(new ConcurrencyLimitClearedError());
90
+ };
91
+
92
+ return limiter as ConcurrencyLimiter;
93
+ }
94
+
95
+ export interface RetryOptions {
96
+ readonly retries?: number;
97
+ readonly minTimeout?: number;
98
+ readonly maxTimeout?: number;
99
+ readonly factor?: number;
100
+ readonly jitter?: boolean;
101
+ readonly shouldRetry?: (error: unknown, attempt: number) => boolean;
102
+ }
103
+
104
+ /**
105
+ * Executes an async task with exponential backoff and jitter.
106
+ */
107
+ export async function withRetry<T>(
108
+ task: (attempt: number) => Promise<T>,
109
+ options: RetryOptions = {},
110
+ ): Promise<T> {
111
+ const retries = options.retries ?? 3;
112
+ const minTimeout = options.minTimeout ?? 200;
113
+ const maxTimeout = options.maxTimeout ?? 3000;
114
+ const factor = options.factor ?? 2;
115
+ const jitter = options.jitter ?? true;
116
+ const shouldRetry = options.shouldRetry ?? (() => true);
117
+
118
+ let attempt = 0;
119
+ while (true) {
120
+ attempt++;
121
+ try {
122
+ return await task(attempt);
123
+ } catch (cause) {
124
+ if (attempt > retries || !shouldRetry(cause, attempt)) {
125
+ throw cause;
126
+ }
127
+ const baseDelay = Math.min(minTimeout * Math.pow(factor, attempt - 1), maxTimeout);
128
+ const delay = jitter ? baseDelay * (0.5 + Math.random() * 0.5) : baseDelay;
129
+ await new Promise((resolve) => setTimeout(resolve, delay));
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Safe DataProvider contract that returns `Promise<Result<T, DomainError>>`
136
+ * for imperative workflows, scripts, and high-rigor pipelines.
137
+ */
138
+ export interface SafeDataProvider {
139
+ readonly raw: DataProvider;
140
+ getList: (params: GetListParams) => Promise<Result<GetListResult, DomainError>>;
141
+ getOne: (params: GetOneParams) => Promise<Result<GetOneResult, DomainError>>;
142
+ create: (params: CreateParams) => Promise<Result<CreateResult, DomainError>>;
143
+ update: (params: UpdateParams) => Promise<Result<UpdateResult, DomainError>>;
144
+ deleteOne: (params: DeleteParams) => Promise<Result<DeleteResult, DomainError>>;
145
+ getApiUrl: () => string;
146
+ getMany?: ((params: GetManyParams) => Promise<Result<GetManyResult, DomainError>>) | undefined;
147
+ createMany?: ((params: CreateManyParams) => Promise<Result<CreateManyResult, DomainError>>) | undefined;
148
+ updateMany?: ((params: UpdateManyParams) => Promise<Result<UpdateManyResult, DomainError>>) | undefined;
149
+ deleteMany?: ((params: DeleteManyParams) => Promise<Result<DeleteManyResult, DomainError>>) | undefined;
150
+ custom?: ((params: CustomParams) => Promise<Result<CustomResult, DomainError>>) | undefined;
151
+ }
152
+
153
+ /**
154
+ * Wraps an existing DataProvider into a SafeDataProvider returning Result<T, DomainError>.
155
+ */
156
+ export function wrapDataProviderWithResult(provider: DataProvider): SafeDataProvider {
157
+ const getMany = provider.getMany?.bind(provider);
158
+ const createMany = provider.createMany?.bind(provider);
159
+ const updateMany = provider.updateMany?.bind(provider);
160
+ const deleteMany = provider.deleteMany?.bind(provider);
161
+ const custom = provider.custom?.bind(provider);
162
+
163
+ const asResult = <T>(run: () => Promise<T>): Promise<Result<T, DomainError>> => {
164
+ try {
165
+ return fromPromise(Promise.resolve(run()), toDomainError);
166
+ } catch (cause) {
167
+ return Promise.resolve(err(toDomainError(cause)));
168
+ }
169
+ };
170
+
171
+ return {
172
+ raw: provider,
173
+ getApiUrl: () => provider.getApiUrl(),
174
+ getList: (params) => asResult(() => provider.getList(params)),
175
+ getOne: (params) => asResult(() => provider.getOne(params)),
176
+ create: (params) => asResult(() => provider.create(params)),
177
+ update: (params) => asResult(() => provider.update(params)),
178
+ deleteOne: (params) => asResult(() => provider.deleteOne(params)),
179
+ getMany: getMany ? (params) => asResult(() => getMany(params)) : undefined,
180
+ createMany: createMany ? (params) => asResult(() => createMany(params)) : undefined,
181
+ updateMany: updateMany ? (params) => asResult(() => updateMany(params)) : undefined,
182
+ deleteMany: deleteMany ? (params) => asResult(() => deleteMany(params)) : undefined,
183
+ custom: custom ? (params) => asResult(() => custom(params)) : undefined,
184
+ };
185
+ }