@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@svadmin/core",
3
- "version": "0.71.0",
3
+ "version": "0.73.0",
4
4
  "author": "zuohuadong",
5
5
  "repository": {
6
6
  "type": "git",
@@ -150,6 +150,18 @@
150
150
  "./contracts": {
151
151
  "types": "./src/contracts.ts",
152
152
  "default": "./src/contracts.ts"
153
+ },
154
+ "./result": {
155
+ "types": "./src/result.ts",
156
+ "default": "./src/result.ts"
157
+ },
158
+ "./domain-errors": {
159
+ "types": "./src/domain-errors.ts",
160
+ "default": "./src/domain-errors.ts"
161
+ },
162
+ "./resilience": {
163
+ "types": "./src/resilience.ts",
164
+ "default": "./src/resilience.ts"
153
165
  }
154
166
  },
155
167
  "bugs": {
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Color scale generation and theme-token exchange.
3
+ *
4
+ * Capability parity with the Arco ecosystem's `@arco-design/color` + theme
5
+ * editor: derive a tonal scale from one brand color, build light/dark CSS
6
+ * variable bundles, and exchange presets as portable JSON.
7
+ *
8
+ * Boundaries (intentional):
9
+ * - no Less/`modifyVars` layer; output is CSS custom properties only;
10
+ * - no arbitrary expression or code compilation in the payload;
11
+ * - gamut mapping happens in OKLCH so generated values stay valid sRGB.
12
+ */
13
+
14
+ export interface ColorScaleStep {
15
+ /** 1 = lightest, 10 = darkest. */
16
+ step: number;
17
+ /** `oklch(L C H)` string, directly assignable to a CSS variable. */
18
+ value: string;
19
+ /** Clamped sRGB hex, for swatches and contrast checks. */
20
+ hex: string;
21
+ }
22
+
23
+ /** Structural subset of `ColorPreset`; keeps this module rune-free. */
24
+ export interface DerivedColorPreset {
25
+ name: string;
26
+ label: string;
27
+ color: string;
28
+ light: Record<string, string>;
29
+ dark: Record<string, string>;
30
+ }
31
+
32
+ export interface ThemeTokenDocument {
33
+ version: 1;
34
+ presets: DerivedColorPreset[];
35
+ }
36
+
37
+ const HEX_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
38
+ const MAX_PRESETS = 64;
39
+ const MAX_VARIABLES = 64;
40
+
41
+ function clamp01(value: number): number {
42
+ return value < 0 ? 0 : value > 1 ? 1 : value;
43
+ }
44
+
45
+ function srgbToLinear(channel: number): number {
46
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
47
+ }
48
+
49
+ function linearToSrgb(channel: number): number {
50
+ return channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
51
+ }
52
+
53
+ export function parseHex(hex: string): { r: number; g: number; b: number } {
54
+ if (typeof hex !== 'string' || !HEX_PATTERN.test(hex.trim())) {
55
+ throw new TypeError(`Expected a 3- or 6-digit hex color, received: ${String(hex)}`);
56
+ }
57
+ let body = hex.trim().slice(1);
58
+ if (body.length === 3) body = body.split('').map((digit) => digit + digit).join('');
59
+ return {
60
+ r: parseInt(body.slice(0, 2), 16) / 255,
61
+ g: parseInt(body.slice(2, 4), 16) / 255,
62
+ b: parseInt(body.slice(4, 6), 16) / 255,
63
+ };
64
+ }
65
+
66
+ export function hexToOklch(hex: string): { l: number; c: number; h: number } {
67
+ const { r, g, b } = parseHex(hex);
68
+ const lr = srgbToLinear(r);
69
+ const lg = srgbToLinear(g);
70
+ const lb = srgbToLinear(b);
71
+ const l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb;
72
+ const m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb;
73
+ const s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb;
74
+ const l3 = Math.cbrt(l);
75
+ const m3 = Math.cbrt(m);
76
+ const s3 = Math.cbrt(s);
77
+ const okL = 0.2104542553 * l3 + 0.793617785 * m3 - 0.0040720468 * s3;
78
+ const okA = 1.9779984951 * l3 - 2.428592205 * m3 + 0.4505937099 * s3;
79
+ const okB = 0.0259040371 * l3 + 0.7827717662 * m3 - 0.808675766 * s3;
80
+ const hue = (Math.atan2(okB, okA) * 180) / Math.PI;
81
+ return { l: okL, c: Math.hypot(okA, okB), h: hue < 0 ? hue + 360 : hue };
82
+ }
83
+
84
+ /** Convert OKLCH to sRGB channels, or `undefined` when the color is out of gamut. */
85
+ function oklchToRgbUnclamped(l: number, c: number, h: number): { r: number; g: number; b: number } | undefined {
86
+ const radians = (h * Math.PI) / 180;
87
+ const okA = c * Math.cos(radians);
88
+ const okB = c * Math.sin(radians);
89
+ const l3 = l + 0.3963377774 * okA + 0.2158037573 * okB;
90
+ const m3 = l - 0.1055613458 * okA - 0.0638541728 * okB;
91
+ const s3 = l - 0.0894841775 * okA - 1.291485548 * okB;
92
+ const lCube = l3 ** 3;
93
+ const mCube = m3 ** 3;
94
+ const sCube = s3 ** 3;
95
+ const linearR = 4.0767416621 * lCube - 3.3077115913 * mCube + 0.2309699292 * sCube;
96
+ const linearG = -1.2684380046 * lCube + 2.6097574011 * mCube - 0.3413193965 * sCube;
97
+ const linearB = -0.0041960863 * lCube - 0.7034186147 * mCube + 1.707614701 * sCube;
98
+ const epsilon = 1e-6;
99
+ if ([linearR, linearG, linearB].some((channel) => channel < -epsilon || channel > 1 + epsilon)) return undefined;
100
+ return {
101
+ r: clamp01(linearToSrgb(clamp01(linearR))),
102
+ g: clamp01(linearToSrgb(clamp01(linearG))),
103
+ b: clamp01(linearToSrgb(clamp01(linearB))),
104
+ };
105
+ }
106
+
107
+ /** Map an OKLCH color into sRGB by reducing chroma until it fits the gamut. */
108
+ function oklchToRgb(l: number, c: number, h: number): { r: number; g: number; b: number } {
109
+ const lightness = clamp01(l);
110
+ const direct = oklchToRgbUnclamped(lightness, c, h);
111
+ if (direct) return direct;
112
+ let low = 0;
113
+ let high = c;
114
+ let result = oklchToRgbUnclamped(lightness, 0, h) ?? { r: 0, g: 0, b: 0 };
115
+ for (let index = 0; index < 24; index += 1) {
116
+ const mid = (low + high) / 2;
117
+ const candidate = oklchToRgbUnclamped(lightness, mid, h);
118
+ if (candidate) {
119
+ result = candidate;
120
+ low = mid;
121
+ } else {
122
+ high = mid;
123
+ }
124
+ }
125
+ return result;
126
+ }
127
+
128
+ function toHex(channels: { r: number; g: number; b: number }): string {
129
+ const part = (value: number): string => Math.round(clamp01(value) * 255).toString(16).padStart(2, '0');
130
+ return `#${part(channels.r)}${part(channels.g)}${part(channels.b)}`.toUpperCase();
131
+ }
132
+
133
+ export function formatOklch(l: number, c: number, h: number): string {
134
+ const roundedHue = Math.round((((h % 360) + 360) % 360) * 10) / 10;
135
+ return `oklch(${Math.round(l * 1000) / 1000} ${Math.round(c * 1000) / 1000} ${roundedHue})`;
136
+ }
137
+
138
+ function relativeLuminance(hex: string): number {
139
+ const { r, g, b } = parseHex(hex);
140
+ return 0.2126 * srgbToLinear(r) + 0.7152 * srgbToLinear(g) + 0.0722 * srgbToLinear(b);
141
+ }
142
+
143
+ function contrastRatio(a: string, b: string): number {
144
+ const first = relativeLuminance(a);
145
+ const second = relativeLuminance(b);
146
+ const lighter = Math.max(first, second);
147
+ const darker = Math.min(first, second);
148
+ return (lighter + 0.05) / (darker + 0.05);
149
+ }
150
+
151
+ /** Pick the foreground with the higher contrast ratio (WCAG relative luminance). */
152
+ export function pickReadableForeground(backgroundHex: string): string {
153
+ return contrastRatio(backgroundHex, '#FFFFFF') >= contrastRatio(backgroundHex, '#111111')
154
+ ? '#FFFFFF'
155
+ : '#111111';
156
+ }
157
+
158
+ /**
159
+ * Derive a 10-step tonal scale from a brand color.
160
+ * Step 1 is the lightest tint, step 10 the darkest shade; hue is preserved.
161
+ */
162
+ export function generateColorScale(color: string): ColorScaleStep[] {
163
+ const { c: baseChroma, h } = hexToOklch(color);
164
+ const lightest = 0.975;
165
+ const darkest = 0.26;
166
+ const steps: ColorScaleStep[] = [];
167
+ for (let step = 1; step <= 10; step += 1) {
168
+ const ratio = (step - 1) / 9;
169
+ const lightness = lightest - (lightest - darkest) * ratio;
170
+ // Chroma peaks in the mid tones so the endpoints stay near-neutral.
171
+ const chroma = baseChroma * (0.35 + 0.65 * Math.sin(Math.PI * (0.15 + 0.7 * ratio)));
172
+ const rgb = oklchToRgb(lightness, chroma, h);
173
+ steps.push({ step, value: formatOklch(lightness, chroma, h), hex: toHex(rgb) });
174
+ }
175
+ return steps;
176
+ }
177
+
178
+ function chartPalette(scale: ColorScaleStep[], hue: number, chroma: number, lightness: number): Record<string, string> {
179
+ const offsets = [0, 32, -32, 64, -64];
180
+ return Object.fromEntries(offsets.map((offset, index) => [
181
+ `--chart-${index + 1}`,
182
+ index === 0 ? scale[5]?.value as string : formatOklch(lightness, chroma, hue + offset),
183
+ ]));
184
+ }
185
+
186
+ /**
187
+ * Build light/dark CSS variable bundles for one brand color.
188
+ * Keys mirror the built-in presets so `registerColorPreset` can consume it.
189
+ */
190
+ export function deriveColorPreset(input: { name: string; label?: string; color: string }): DerivedColorPreset {
191
+ const name = input.name?.trim();
192
+ if (!name) throw new TypeError('deriveColorPreset requires a non-empty name');
193
+ const color = input.color?.trim();
194
+ const source = hexToOklch(color);
195
+ const scale = generateColorScale(color);
196
+ const lightPrimary = scale[5] as ColorScaleStep;
197
+ const darkPrimary = scale[3] as ColorScaleStep;
198
+ const lightForeground = pickReadableForeground(lightPrimary.hex);
199
+ const darkForeground = pickReadableForeground(darkPrimary.hex);
200
+
201
+ return {
202
+ name,
203
+ label: input.label?.trim() || name,
204
+ color: color.toUpperCase(),
205
+ light: {
206
+ '--primary': lightPrimary.value,
207
+ '--primary-foreground': lightForeground,
208
+ '--ring': lightPrimary.value,
209
+ '--sidebar-primary': lightPrimary.value,
210
+ '--sidebar-primary-foreground': lightForeground,
211
+ '--sidebar-ring': lightPrimary.value,
212
+ ...chartPalette(scale, source.h, source.c, source.l),
213
+ },
214
+ dark: {
215
+ '--primary': darkPrimary.value,
216
+ '--primary-foreground': darkForeground,
217
+ '--ring': scale[4]?.value as string,
218
+ '--sidebar-primary': darkPrimary.value,
219
+ '--sidebar-primary-foreground': darkForeground,
220
+ '--sidebar-ring': scale[4]?.value as string,
221
+ ...chartPalette(scale, source.h, source.c * 1.05, Math.min(0.82, source.l + 0.12)),
222
+ },
223
+ };
224
+ }
225
+
226
+ function assertVariableMap(value: unknown, label: string): asserts value is Record<string, string> {
227
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
228
+ throw new TypeError(`${label} must be an object of CSS variable values`);
229
+ }
230
+ const entries = Object.entries(value);
231
+ if (entries.length === 0 || entries.length > MAX_VARIABLES) {
232
+ throw new TypeError(`${label} must declare between 1 and ${MAX_VARIABLES} variables`);
233
+ }
234
+ for (const [key, variable] of entries) {
235
+ if (!/^--[a-z0-9-]{1,64}$/i.test(key)) throw new TypeError(`${label} has an invalid CSS variable name: ${key}`);
236
+ if (typeof variable !== 'string' || variable.trim() === '' || variable.length > 200) {
237
+ throw new TypeError(`${label}.${key} must be a non-empty string`);
238
+ }
239
+ // Token exchange is a data contract: only color syntax, never arbitrary CSS.
240
+ if (!/^(?:oklch\(|#|rgb\(|hsl\(|var\(--)/i.test(variable.trim()) || /[;{}]/.test(variable)) {
241
+ throw new TypeError(`${label}.${key} is not a color token value: ${variable}`);
242
+ }
243
+ }
244
+ }
245
+
246
+ /** Serialize presets into a portable, versioned document. */
247
+ export function exportThemeTokens(presets: readonly DerivedColorPreset[]): ThemeTokenDocument {
248
+ return {
249
+ version: 1,
250
+ presets: presets.map((preset) => ({
251
+ name: preset.name,
252
+ label: preset.label,
253
+ color: preset.color,
254
+ light: { ...preset.light },
255
+ dark: { ...preset.dark },
256
+ })),
257
+ };
258
+ }
259
+
260
+ /** Validate and clone a token document without mutating shared state. */
261
+ export function parseThemeTokens(payload: unknown): DerivedColorPreset[] {
262
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
263
+ throw new TypeError('Theme token document must be an object');
264
+ }
265
+ const document = payload as Partial<ThemeTokenDocument>;
266
+ if (document.version !== 1) throw new TypeError('Unsupported theme token document version; expected 1');
267
+ if (!Array.isArray(document.presets) || document.presets.length === 0 || document.presets.length > MAX_PRESETS) {
268
+ throw new TypeError(`Theme token document must declare between 1 and ${MAX_PRESETS} presets`);
269
+ }
270
+ const seen = new Set<string>();
271
+ return document.presets.map((raw, index) => {
272
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
273
+ throw new TypeError(`Theme token preset at index ${index} must be an object`);
274
+ }
275
+ const { name, label, color } = raw as Partial<DerivedColorPreset>;
276
+ if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(name)) {
277
+ throw new TypeError(`Theme token preset at index ${index} has an invalid name`);
278
+ }
279
+ if (seen.has(name)) throw new TypeError(`Duplicate theme token preset: ${name}`);
280
+ seen.add(name);
281
+ if (typeof color !== 'string' || !HEX_PATTERN.test(color.trim())) {
282
+ throw new TypeError(`Theme token preset "${name}" must declare a hex color`);
283
+ }
284
+ assertVariableMap(raw.light, `${name}.light`);
285
+ assertVariableMap(raw.dark, `${name}.dark`);
286
+ return {
287
+ name,
288
+ label: typeof label === 'string' && label.trim() !== '' ? label.trim().slice(0, 64) : name,
289
+ color: color.trim().toUpperCase(),
290
+ light: { ...raw.light },
291
+ dark: { ...raw.dark },
292
+ };
293
+ });
294
+ }
@@ -18,6 +18,8 @@ import { auditWithProvider } from './audit';
18
18
  import { HttpError } from './types';
19
19
  import { useTranslation } from './i18n.svelte';
20
20
  import { toast } from './toast.svelte';
21
+ import { ok, err, type Result as SafeResult } from './result';
22
+ import { toDomainError, type DomainError } from './domain-errors';
21
23
 
22
24
  export interface ContractCreateOptions<S extends ContractSchemas> {
23
25
  resource: ResourceContract<S>;
@@ -331,13 +333,21 @@ export function useContractCreate<S extends ContractSchemas>(options: ContractCr
331
333
  mutate(params: ContractCreateParams<S>, callbacks?: Callbacks<S>): void {
332
334
  void mutateAsync(params, callbacks).catch(() => {});
333
335
  },
336
+ async safeMutate(params: ContractCreateParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
337
+ try {
338
+ const res = await mutateAsync(params, callbacks);
339
+ return ok(res.data);
340
+ } catch (cause) {
341
+ return err(toDomainError(cause));
342
+ }
343
+ },
334
344
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
335
345
  });
336
346
  const idle: typeof result = {
337
347
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
338
348
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
339
349
  status: 'idle', submittedAt: 0, variables: undefined,
340
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
350
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
341
351
  };
342
352
  const view = createQueryResultView(() => {
343
353
  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
 
@@ -377,13 +379,21 @@ export function useContractCreateMany<S extends ContractSchemas>(options: Contra
377
379
  mutate(params: ContractCreateManyParams<S>, callbacks?: Callbacks<S>): void {
378
380
  void mutateAsync(params, callbacks).catch(() => {});
379
381
  },
382
+ async safeMutate(params: ContractCreateManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
383
+ try {
384
+ const res = await mutateAsync(params, callbacks);
385
+ return ok(res.data);
386
+ } catch (cause) {
387
+ return err(toDomainError(cause));
388
+ }
389
+ },
380
390
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
381
391
  });
382
392
  const idle: typeof result = {
383
393
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
384
394
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
385
395
  status: 'idle', submittedAt: 0, variables: undefined,
386
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
396
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
387
397
  };
388
398
  const view = createQueryResultView(() => {
389
399
  const invocation = mutation.variables;
@@ -17,6 +17,8 @@ import { auditWithProvider } from './audit';
17
17
  import { HttpError, UndoError } from './types';
18
18
  import { useTranslation } from './i18n.svelte';
19
19
  import { toast, getToasts, removeToast } 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 { ContractDeleteParams } from './delete-contract';
22
24
  export interface ContractDeleteOptions<S extends ContractSchemas> {
@@ -384,13 +386,21 @@ export function useContractDelete<S extends ContractSchemas>(options: ContractDe
384
386
  mutate(params: ContractDeleteParams<S>, callbacks?: Callbacks<S>): void {
385
387
  void mutateAsync(params, callbacks).catch(() => {});
386
388
  },
389
+ async safeMutate(params: ContractDeleteParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
390
+ try {
391
+ const res = await mutateAsync(params, callbacks);
392
+ return ok(res.data);
393
+ } catch (cause) {
394
+ return err(toDomainError(cause));
395
+ }
396
+ },
387
397
  reset() { latestToken = undefined; clearActive(); mutation.reset(); },
388
398
  });
389
399
  const idle: typeof result = {
390
400
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
391
401
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
392
402
  status: 'idle', submittedAt: 0, variables: undefined,
393
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
403
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
394
404
  };
395
405
  const view = createQueryResultView(() => {
396
406
  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 { DeleteManyPartialError, 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
 
@@ -386,13 +388,21 @@ export function useContractDeleteMany<S extends ContractSchemas>(options: Contra
386
388
  mutate(params: ContractDeleteManyParams<S>, callbacks?: Callbacks<S>): void {
387
389
  void mutateAsync(params, callbacks).catch(() => {});
388
390
  },
391
+ async safeMutate(params: ContractDeleteManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
392
+ try {
393
+ const res = await mutateAsync(params, callbacks);
394
+ return ok(res.data);
395
+ } catch (cause) {
396
+ return err(toDomainError(cause));
397
+ }
398
+ },
389
399
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
390
400
  });
391
401
  const idle: typeof result = {
392
402
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
393
403
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
394
404
  status: 'idle', submittedAt: 0, variables: undefined,
395
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
405
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
396
406
  };
397
407
  const view = createQueryResultView(() => {
398
408
  const invocation = mutation.variables;