@svadmin/core 0.70.0 → 0.72.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,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
+ }
package/src/result.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * High-rigor Result<T, E> algebraic data type for safe, typed error handling
3
+ * without throwing exceptions.
4
+ */
5
+
6
+ export interface Ok<T> {
7
+ readonly ok: true;
8
+ readonly value: T;
9
+ readonly error?: never;
10
+ }
11
+
12
+ export interface Err<E> {
13
+ readonly ok: false;
14
+ readonly error: E;
15
+ readonly value?: never;
16
+ }
17
+
18
+ export type Result<T, E> = Ok<T> | Err<E>;
19
+
20
+ export function ok<T>(value: T): Ok<T> {
21
+ return { ok: true, value };
22
+ }
23
+
24
+ export function err<E>(error: E): Err<E> {
25
+ return { ok: false, error };
26
+ }
27
+
28
+ export function isOk<T, E>(result: Result<T, E>): result is Ok<T> {
29
+ return result.ok === true;
30
+ }
31
+
32
+ export function isErr<T, E>(result: Result<T, E>): result is Err<E> {
33
+ return result.ok === false;
34
+ }
35
+
36
+ export function unwrapResult<T, E>(result: Result<T, E>): T {
37
+ if (result.ok) {
38
+ return result.value;
39
+ }
40
+ throw result.error;
41
+ }
42
+
43
+ export function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T {
44
+ return result.ok ? result.value : fallback;
45
+ }
46
+
47
+ export function mapResult<T, E, U>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {
48
+ if (result.ok) {
49
+ return ok(fn(result.value));
50
+ }
51
+ return result;
52
+ }
53
+
54
+ export function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {
55
+ if (!result.ok) {
56
+ return err(fn(result.error));
57
+ }
58
+ return result;
59
+ }
60
+
61
+ export function flatMapResult<T, E, U>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {
62
+ if (result.ok) {
63
+ return fn(result.value);
64
+ }
65
+ return result;
66
+ }
67
+
68
+ export function matchResult<T, E, R>(
69
+ result: Result<T, E>,
70
+ patterns: {
71
+ ok: (value: T) => R;
72
+ err: (error: E) => R;
73
+ },
74
+ ): R {
75
+ return result.ok ? patterns.ok(result.value) : patterns.err(result.error);
76
+ }
77
+
78
+ export function fromThrowable<T, E = unknown>(
79
+ fn: () => T,
80
+ onError: (cause: unknown) => E,
81
+ ): Result<T, E> {
82
+ try {
83
+ return ok(fn());
84
+ } catch (cause) {
85
+ return err(onError(cause));
86
+ }
87
+ }
88
+
89
+ export async function fromPromise<T, E = unknown>(
90
+ promise: Promise<T>,
91
+ onError: (cause: unknown) => E,
92
+ ): Promise<Result<T, E>> {
93
+ try {
94
+ const value = await promise;
95
+ return ok(value);
96
+ } catch (cause) {
97
+ return err(onError(cause));
98
+ }
99
+ }
@@ -17,6 +17,8 @@ import { auditWithProvider } from './audit';
17
17
  import { HttpError } from './types';
18
18
  import { useTranslation } from './i18n.svelte';
19
19
  import { toast } from './toast.svelte';
20
+ import { ok, err, type Result as SafeResult } from './result';
21
+ import { toDomainError, type DomainError } from './domain-errors';
20
22
 
21
23
  export type { ContractUpdateParams } from './update-contract';
22
24
  export interface ContractUpdateOptions<S extends ContractSchemas> {
@@ -328,13 +330,21 @@ export function useContractUpdate<S extends ContractSchemas>(options: ContractUp
328
330
  mutate(params: ContractUpdateParams<S>, callbacks?: Callbacks<S>): void {
329
331
  void mutateAsync(params, callbacks).catch(() => {});
330
332
  },
333
+ async safeMutate(params: ContractUpdateParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
334
+ try {
335
+ const res = await mutateAsync(params, callbacks);
336
+ return ok(res.data);
337
+ } catch (cause) {
338
+ return err(toDomainError(cause));
339
+ }
340
+ },
331
341
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
332
342
  });
333
343
  const idle: typeof result = {
334
344
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
335
345
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
336
346
  status: 'idle', submittedAt: 0, variables: undefined,
337
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
347
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
338
348
  };
339
349
  const view = createQueryResultView(() => {
340
350
  const invocation = mutation.variables;
@@ -15,6 +15,8 @@ import { getAdminOptions } from './options.svelte';
15
15
  import { captureAuthLiveScope, clearAuthQueries, handleAuthError } from './auth-hooks.svelte';
16
16
  import { auditWithProvider } from './audit';
17
17
  import { HttpError } from './types';
18
+ import { ok, err, type Result as SafeResult } from './result';
19
+ import { toDomainError, type DomainError } from './domain-errors';
18
20
  import { useTranslation } from './i18n.svelte';
19
21
  import { toast } from './toast.svelte';
20
22
 
@@ -357,13 +359,21 @@ export function useContractUpdateMany<S extends ContractSchemas>(options: Contra
357
359
  mutate(params: ContractUpdateManyParams<S>, callbacks?: Callbacks<S>): void {
358
360
  void mutateAsync(params, callbacks).catch(() => {});
359
361
  },
362
+ async safeMutate(params: ContractUpdateManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
363
+ try {
364
+ const res = await mutateAsync(params, callbacks);
365
+ return ok(res.data);
366
+ } catch (cause) {
367
+ return err(toDomainError(cause));
368
+ }
369
+ },
360
370
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
361
371
  });
362
372
  const idle: typeof result = {
363
373
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
364
374
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
365
375
  status: 'idle', submittedAt: 0, variables: undefined,
366
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
376
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
367
377
  };
368
378
  const view = createQueryResultView(() => {
369
379
  const invocation = mutation.variables;