@svadmin/core 0.69.2 → 0.69.3

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/src/inferencer.ts CHANGED
@@ -5,6 +5,12 @@
5
5
  * Can also generate copy-paste-ready Svelte component code.
6
6
  */
7
7
  import type { FieldDefinition, ResourceDefinition } from './types';
8
+ import {
9
+ closedValueExpression,
10
+ getContractExpression,
11
+ propertyKey,
12
+ rememberContractExpression,
13
+ } from './inferencer-contract';
8
14
 
9
15
  // ─── Field Type Inference ────────────────────────────────────
10
16
 
@@ -98,7 +104,8 @@ export type InferReviewWarningCode =
98
104
  | 'nullable-field'
99
105
  | 'mixed-types'
100
106
  | 'heuristic-relation'
101
- | 'heuristic-select';
107
+ | 'heuristic-select'
108
+ | 'unconstrained-field';
102
109
 
103
110
  export interface InferReviewWarning {
104
111
  code: InferReviewWarningCode;
@@ -135,7 +142,7 @@ export function inferResource(
135
142
  return {
136
143
  fields: [],
137
144
  resource: emptyResource,
138
- code: `// No data available to infer fields for "${resourceName}".`,
145
+ code: `// No data available to infer fields for "${resourceName}".\n${generateCode(emptyResource)}`,
139
146
  typeboxCode: generateTypeBoxSchemaCode(emptyResource),
140
147
  review: {
141
148
  needsReview: true,
@@ -242,6 +249,24 @@ export function inferResource(
242
249
  field.options = [...uniqueStrings].map(v => ({ label: capitalize(v), value: v }));
243
250
  }
244
251
 
252
+ if (field.type === 'json' || field.type === 'richtext') {
253
+ const observed = sampleData.flatMap((row) => (
254
+ Object.prototype.hasOwnProperty.call(row, key) ? [row[key]] : []
255
+ ));
256
+ const expression = closedValueExpression(observed, 0, new WeakSet());
257
+ if (expression) {
258
+ rememberContractExpression(field, expression);
259
+ } else if (field.type === 'richtext') {
260
+ rememberContractExpression(field, 'Type.String()');
261
+ } else {
262
+ warnings.push({
263
+ code: 'unconstrained-field',
264
+ field: key,
265
+ message: `Field "${key}" is omitted from the strict ResourceContract because its sample shape is not a closed JSON value. Author the contract by hand.`,
266
+ });
267
+ }
268
+ }
269
+
245
270
  fields.push(field);
246
271
  }
247
272
 
@@ -293,40 +318,171 @@ export function inferResource(
293
318
 
294
319
  // ─── Code Generation ─────────────────────────────────────────
295
320
 
296
- function generateCode(resource: ResourceDefinition): string {
297
- const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
298
- const fieldsCode = resource.fields.map((f: FieldDefinition) => {
299
- const lines = [
300
- ` { key: '${esc(f.key)}', label: '${esc(f.label)}', type: '${f.type}'`,
301
- ];
302
- if (f.sortable) lines.push(` sortable: true`);
303
- if (f.searchable) lines.push(` searchable: true`);
304
- if (f.showInList === false) lines.push(` showInList: false`);
305
- if (f.showInForm === false) lines.push(` showInForm: false`);
306
- if (f.resource) {
307
- lines.push(` resource: '${f.resource}'`);
308
- lines.push(` optionLabel: '${f.optionLabel}'`);
309
- lines.push(` optionValue: '${f.optionValue}'`);
310
- }
311
- if (f.options) {
312
- lines.push(` options: ${JSON.stringify(f.options)}`);
313
- }
321
+ function moduleName(resource: ResourceDefinition): string {
322
+ const safe = resource.name.replace(/[^A-Za-z0-9_$]/g, '_');
323
+ return /^[A-Za-z_$]/.test(safe) ? safe : `resource_${safe}`;
324
+ }
325
+
326
+ /** Closed TypeBox expression, or null when the value cannot be a strict contract field. */
327
+ function contractTypeExpression(field: FieldDefinition): string | null {
328
+ const esc = (value: string) => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
329
+ switch (field.type) {
330
+ case 'number':
331
+ return 'Type.Number()';
332
+ case 'boolean':
333
+ return 'Type.Boolean()';
334
+ case 'date':
335
+ return "Type.String({ format: 'date-time' })";
336
+ case 'email':
337
+ return "Type.String({ format: 'email' })";
338
+ case 'url':
339
+ case 'image':
340
+ return "Type.String({ format: 'uri' })";
341
+ case 'phone':
342
+ return "Type.String({ pattern: '^\\\\+?[\\\\d\\\\s\\\\-()]{7,}$' })";
343
+ case 'tags':
344
+ return 'Type.Array(Type.String())';
345
+ case 'images':
346
+ return "Type.Array(Type.String({ format: 'uri' }))";
347
+ case 'select':
348
+ if (field.options && field.options.length > 0) {
349
+ const literals = field.options.map((option) => `Type.Literal('${esc(String(option.value))}')`).join(', ');
350
+ return `Type.Union([${literals}])`;
351
+ }
352
+ return 'Type.String()';
353
+ case 'relation':
354
+ return 'Type.Union([Type.String(), Type.Number()])';
355
+ case 'daterange':
356
+ return 'Type.Union([Type.Object({ start: Type.Union([Type.String(), Type.Null()]), end: Type.Union([Type.String(), Type.Null()]) }, { additionalProperties: false }), Type.Null()])';
357
+ case 'json':
358
+ return getContractExpression(field) ?? null;
359
+ case 'richtext':
360
+ return getContractExpression(field) ?? 'Type.String()';
361
+ case 'datetime':
362
+ case 'time':
363
+ case 'textarea':
364
+ case 'text':
365
+ case 'color':
366
+ default:
367
+ return 'Type.String()';
368
+ }
369
+ }
370
+
371
+ function idTypeExpression(field: FieldDefinition | undefined): string {
372
+ if (!field) return 'Type.String()';
373
+ if (field.type === 'number') return 'Type.Number()';
374
+ if (field.type === 'relation') return 'Type.Union([Type.String(), Type.Number()])';
375
+ return 'Type.String()';
376
+ }
314
377
 
315
- return lines.join(',\n') + ' }';
378
+ function schemaProperty(key: string, expression: string, optional: boolean): string {
379
+ const value = optional ? `Type.Optional(${expression})` : expression;
380
+ return ` ${propertyKey(key)}: ${value},`;
381
+ }
382
+
383
+ function objectConst(name: string, properties: string[]): string {
384
+ const body = properties.length > 0 ? `\n${properties.join('\n')}\n` : '\n';
385
+ return `const ${name} = Type.Object({${body}}, { additionalProperties: false });`;
386
+ }
387
+
388
+ function definitionFieldLines(fields: FieldDefinition[]): string {
389
+ const esc = (value: string) => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
390
+ return fields.map((field) => {
391
+ const lines = [` { key: '${esc(field.key)}', label: '${esc(field.label)}', type: '${field.type}'`];
392
+ if (field.sortable) lines.push(' sortable: true');
393
+ if (field.searchable) lines.push(' searchable: true');
394
+ if (field.showInList === false) lines.push(' showInList: false');
395
+ if (field.showInForm === false) lines.push(' showInForm: false');
396
+ if (field.resource) {
397
+ lines.push(` resource: '${esc(field.resource)}'`);
398
+ lines.push(` optionLabel: '${esc(field.optionLabel ?? 'name')}'`);
399
+ lines.push(` optionValue: '${esc(field.optionValue ?? 'id')}'`);
400
+ }
401
+ if (field.options) lines.push(` options: ${JSON.stringify(field.options)}`);
402
+ return `${lines.join(',\n')} }`;
316
403
  }).join(',\n');
404
+ }
405
+
406
+ function contractParts(resource: ResourceDefinition): { idField: FieldDefinition | undefined; writable: FieldDefinition[] } {
407
+ const sourceKey = resource.primaryKey ?? 'id';
408
+ const idField = resource.fields.find((field) => field.key === sourceKey) ?? resource.fields.find((field) => field.key === 'id');
409
+ const writable = resource.fields.filter((field) => (
410
+ field.key !== sourceKey
411
+ && field.key !== 'id'
412
+ && field.showInForm !== false
413
+ && contractTypeExpression(field) !== null
414
+ ));
415
+ return { idField, writable };
416
+ }
417
+
418
+ function definitionFields(resource: ResourceDefinition): FieldDefinition[] {
419
+ const sourceKey = resource.primaryKey ?? 'id';
420
+ const idField = resource.fields.find((field) => field.key === sourceKey) ?? resource.fields.find((field) => field.key === 'id');
421
+ const rest = resource.fields.filter((field) => field.key !== sourceKey && field.key !== 'id');
422
+ const idDefinition: FieldDefinition = idField
423
+ ? { ...idField, key: 'id', showInForm: false }
424
+ : { key: 'id', label: 'ID', type: 'text', showInForm: false, showInList: false };
425
+ return [idDefinition, ...rest];
426
+ }
317
427
 
318
- return `import type { ResourceDefinition } from '@svadmin/core';
428
+ function handAuthoredContractNotes(resource: ResourceDefinition): string {
429
+ const notes = resource.fields.flatMap((field) => {
430
+ if (field.type !== 'json' && field.type !== 'richtext') return [];
431
+ if (contractTypeExpression(field) !== null) return [];
432
+ return [
433
+ `// @svadmin hand-authored-contract ${JSON.stringify(field.key)}: ${field.type} is omitted from the strict contract because its sample shape is not a closed JSON value. Author a closed Type.Object schema before records containing this field can pass validation.`,
434
+ ];
435
+ });
436
+ return notes.length > 0 ? `${notes.join('\n')}\n` : '';
437
+ }
438
+
439
+ function generateCode(resource: ResourceDefinition): string {
440
+ const name = moduleName(resource);
441
+ const literalName = resource.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
442
+ const literalLabel = resource.label.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
443
+ const { idField, writable } = contractParts(resource);
444
+ const idType = idTypeExpression(idField);
445
+ const recordProps = [
446
+ schemaProperty('id', idType, false),
447
+ ...writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', field.required !== true)),
448
+ ];
449
+ const createProps = writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', field.required !== true));
450
+ const updateProps = writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', true));
451
+ const sourceKey = resource.primaryKey ?? 'id';
452
+ const projection = sourceKey === 'id'
453
+ ? ''
454
+ : `// Source primary key "${sourceKey.replace(/"/g, '\\"')}" is projected onto the contract id.\n`;
455
+ return `import { Type } from 'typebox';
456
+ import { defineResource, type AdminResourceDefinition } from '@svadmin/core';
457
+
458
+ ${projection}${handAuthoredContractNotes(resource)}${objectConst(`${name}RecordSchema`, recordProps)}
459
+
460
+ ${objectConst(`${name}CreateSchema`, createProps)}
461
+
462
+ ${objectConst(`${name}UpdateSchema`, updateProps)}
463
+
464
+ ${objectConst(`${name}DeleteSchema`, [schemaProperty('id', idType, false)])}
465
+
466
+ /** Runtime contract consumed by AutoTable and AutoForm through resolveResourceContract(). */
467
+ export const ${name}Resource = defineResource('${literalName}', {
468
+ record: ${name}RecordSchema,
469
+ create: ${name}CreateSchema,
470
+ update: ${name}UpdateSchema,
471
+ delete: ${name}DeleteSchema,
472
+ });
319
473
 
320
- export const ${resource.name}Resource: ResourceDefinition = {
321
- name: '${resource.name}',
322
- label: '${resource.label}',
323
- primaryKey: '${resource.primaryKey ?? 'id'}',
324
- canCreate: true,
325
- canEdit: true,
326
- canDelete: true,
327
- canShow: true,
474
+ /** Register this definition on the admin config resources array. */
475
+ export const ${name}Definition: AdminResourceDefinition = {
476
+ name: '${literalName}',
477
+ label: '${literalLabel}',
478
+ primaryKey: 'id',
479
+ canCreate: ${resource.canCreate ?? true},
480
+ canEdit: ${resource.canEdit ?? true},
481
+ canDelete: ${resource.canDelete ?? true},
482
+ canShow: ${resource.canShow ?? true},
483
+ contract: ${name}Resource,
328
484
  fields: [
329
- ${fieldsCode}
485
+ ${definitionFieldLines(definitionFields(resource))}
330
486
  ],
331
487
  };
332
488
  `;
@@ -336,12 +492,16 @@ ${fieldsCode}
336
492
  * Generate Svelte 5 ListPage component code for a resource.
337
493
  */
338
494
  export function generateListPageCode(resource: ResourceDefinition): string {
495
+ const name = moduleName(resource);
339
496
  return `<script lang="ts">
340
497
  import { ListPage, AutoTable } from '@svadmin/ui';
498
+ import { ${name}Definition } from '../${resource.name}.resource';
499
+
500
+ const resourceName = ${name}Definition.name;
341
501
  </script>
342
502
 
343
- <ListPage resourceName="${resource.name}">
344
- <AutoTable resourceName="${resource.name}" />
503
+ <ListPage {resourceName}>
504
+ <AutoTable {resourceName} />
345
505
  </ListPage>
346
506
  `;
347
507
  }
@@ -350,12 +510,16 @@ export function generateListPageCode(resource: ResourceDefinition): string {
350
510
  * Generate Svelte 5 CreatePage component code for a resource.
351
511
  */
352
512
  export function generateCreatePageCode(resource: ResourceDefinition): string {
513
+ const name = moduleName(resource);
353
514
  return `<script lang="ts">
354
515
  import { CreatePage, AutoForm } from '@svadmin/ui';
516
+ import { ${name}Definition } from '../${resource.name}.resource';
517
+
518
+ const resourceName = ${name}Definition.name;
355
519
  </script>
356
520
 
357
- <CreatePage resourceName="${resource.name}">
358
- <AutoForm resourceName="${resource.name}" mode="create" />
521
+ <CreatePage {resourceName}>
522
+ <AutoForm {resourceName} mode="create" />
359
523
  </CreatePage>
360
524
  `;
361
525
  }
@@ -364,18 +528,21 @@ export function generateCreatePageCode(resource: ResourceDefinition): string {
364
528
  * Generate Svelte 5 EditPage component code for a resource.
365
529
  */
366
530
  export function generateEditPageCode(resource: ResourceDefinition): string {
531
+ const name = moduleName(resource);
367
532
  return `<script lang="ts">
368
533
  import { EditPage, AutoForm } from '@svadmin/ui';
534
+ import { ${name}Definition } from '../${resource.name}.resource';
369
535
 
370
536
  interface Props {
371
537
  id?: string | number;
372
538
  }
373
539
 
374
540
  let { id }: Props = $props();
541
+ const resourceName = ${name}Definition.name;
375
542
  </script>
376
543
 
377
- <EditPage resourceName="${resource.name}" {id}>
378
- <AutoForm resourceName="${resource.name}" {id} mode="edit" />
544
+ <EditPage {resourceName} {id}>
545
+ <AutoForm {resourceName} {id} mode="edit" />
379
546
  </EditPage>
380
547
  `;
381
548
  }
@@ -384,18 +551,21 @@ export function generateEditPageCode(resource: ResourceDefinition): string {
384
551
  * Generate Svelte 5 ShowPage component code for a resource.
385
552
  */
386
553
  export function generateShowPageCode(resource: ResourceDefinition): string {
554
+ const name = moduleName(resource);
387
555
  return `<script lang="ts">
388
556
  import { ShowPage, AutoForm } from '@svadmin/ui';
557
+ import { ${name}Definition } from '../${resource.name}.resource';
389
558
 
390
559
  interface Props {
391
560
  id?: string | number;
392
561
  }
393
562
 
394
563
  let { id }: Props = $props();
564
+ const resourceName = ${name}Definition.name;
395
565
  </script>
396
566
 
397
- <ShowPage resourceName="${resource.name}" {id}>
398
- <AutoForm resourceName="${resource.name}" {id} mode="show" />
567
+ <ShowPage {resourceName} {id}>
568
+ <AutoForm {resourceName} {id} mode="show" />
399
569
  </ShowPage>
400
570
  `;
401
571
  }
@@ -407,6 +577,11 @@ export function generateResourceCode(resource: ResourceDefinition): string {
407
577
  return generateCode(resource);
408
578
  }
409
579
 
580
+ /** Alias that makes the ResourceContract output explicit for callers. */
581
+ export function generateResourceContractCode(resource: ResourceDefinition): string {
582
+ return generateCode(resource);
583
+ }
584
+
410
585
  /**
411
586
  * Generate TypeScript code for TypeBox schema definition.
412
587
  */
@@ -451,7 +626,7 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
451
626
  typeDef = "Type.Array(Type.String({ format: 'uri' }))";
452
627
  break;
453
628
  case 'json':
454
- typeDef = 'Type.Record(Type.String(), Type.Unknown())';
629
+ typeDef = getContractExpression(f) ?? 'Type.Record(Type.String(), Type.Unknown())';
455
630
  break;
456
631
  case 'select':
457
632
  if (f.options && f.options.length > 0) {
@@ -464,8 +639,10 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
464
639
  case 'relation':
465
640
  typeDef = 'Type.Union([Type.String(), Type.Number()])';
466
641
  break;
467
- case 'textarea':
468
642
  case 'richtext':
643
+ typeDef = getContractExpression(f) ?? 'Type.String()';
644
+ break;
645
+ case 'textarea':
469
646
  case 'text':
470
647
  default:
471
648
  typeDef = 'Type.String()';
@@ -486,7 +663,7 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
486
663
 
487
664
  export const ${typeName}Schema = Type.Object({
488
665
  ${schemaProps}
489
- });
666
+ }, { additionalProperties: false });
490
667
 
491
668
  export type ${typeName} = Static<typeof ${typeName}Schema>;
492
669
  `;
@@ -19,6 +19,7 @@ import { decodeBaseRecord, decodeListResult, decodeOneResult, decodeManyResult,
19
19
  import { HttpError } from './types';
20
20
  import { extendReactiveMembers } from './reactive-projection';
21
21
  import { captureQueryProvider, snapshotListParams, snapshotOneParams, snapshotManyParams } from './query-snapshot';
22
+ import { applyListSelect, listQuerySettings, type ResourceQueryOptions } from './query-options';
22
23
 
23
24
  // ─── useList ───────────────────────────────────────────────────
24
25
 
@@ -31,7 +32,7 @@ export interface UseListOptions<_TData extends BaseRecord=BaseRecord,_TError=Htt
31
32
  filters?: Filter[];
32
33
  meta?: Record<string,unknown>;
33
34
  dataProviderName?: string;
34
- queryOptions?: { staleTime?: number; enabled?: boolean; gcTime?: number; refetchOnWindowFocus?: boolean };
35
+ queryOptions?: ResourceQueryOptions<GetListResult<_TData>>;
35
36
  successNotification?: NotificationConfig;
36
37
  errorNotification?: NotificationConfig;
37
38
  liveMode?: LiveMode;
@@ -63,6 +64,7 @@ export function createListQuery<TData extends BaseRecord>(
63
64
  resource,...definedOptions({ dataProviderName: opts.dataProviderName,contract: opts.contract,meta: opts.meta }),
64
65
  });
65
66
  const queryOptions=opts.queryOptions;
67
+ const settings=listQuerySettings(queryOptions);
66
68
 
67
69
  // Inject a parent filter for nested resources.
68
70
  // Consume only parentParams parsed from the path, such as teamId in /teams/123/users,
@@ -94,7 +96,6 @@ export function createListQuery<TData extends BaseRecord>(
94
96
 
95
97
  return {
96
98
  resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
97
- decode: decodeResult,
98
99
  queryKey: adminContext.queryKeys(resource,opts.dataProviderName).data.list(resource,{
99
100
  ...definedOptions({
100
101
  pagination: params.pagination,sorters: params.sorters,filters: params.filters,meta: params.meta,
@@ -107,11 +108,20 @@ export function createListQuery<TData extends BaseRecord>(
107
108
  });
108
109
  return decodeResult(await current.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal }) })));
109
110
  },
110
- enabled: queryOptions?.enabled??true,
111
+ decode: (value): GetListResult<TData> => applyListSelect(
112
+ decodeResult(value),
113
+ queryOptions?.select as ((data: GetListResult<TData>) => GetListResult<TData>) | undefined,
114
+ ),
115
+ enabled: settings.enabled,
111
116
  ...definedOptions({
112
- staleTime: queryOptions?.staleTime??adminOptions.reactQuery?.staleTime,
113
- gcTime: queryOptions?.gcTime??adminOptions.reactQuery?.gcTime,
114
- refetchOnWindowFocus: queryOptions?.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
117
+ staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
118
+ gcTime: settings.gcTime??adminOptions.reactQuery?.gcTime,
119
+ refetchOnWindowFocus: settings.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
120
+ retry: settings.retry,
121
+ retryDelay: settings.retryDelay,
122
+ refetchInterval: settings.refetchInterval,
123
+ refetchIntervalInBackground: settings.refetchIntervalInBackground,
124
+ placeholderData: settings.placeholderData as GetListResult<TData> | ((previousData: GetListResult<TData> | undefined) => GetListResult<TData> | undefined) | undefined,
115
125
  }),
116
126
  };
117
127
  });
@@ -0,0 +1,50 @@
1
+ import { definedOptions } from './defined-options';
2
+
3
+ /**
4
+ * useList / useTable 可以安全转发的 TanStack Query 选项。
5
+ * `select` 在解码之后执行,避免改掉缓存里的原始响应。
6
+ */
7
+ export interface ResourceQueryOptions<TData = unknown> {
8
+ staleTime?: number;
9
+ enabled?: boolean;
10
+ gcTime?: number;
11
+ refetchOnWindowFocus?: boolean | 'always';
12
+ retry?: boolean | number;
13
+ retryDelay?: number | ((failureCount: number, error: unknown) => number);
14
+ refetchInterval?: number | false;
15
+ refetchIntervalInBackground?: boolean;
16
+ placeholderData?: TData | ((previousData: TData | undefined) => TData | undefined);
17
+ select?: (data: TData) => TData;
18
+ }
19
+
20
+ export interface ListQuerySettings<TData = unknown> {
21
+ enabled: boolean;
22
+ staleTime?: number;
23
+ gcTime?: number;
24
+ refetchOnWindowFocus?: boolean | 'always';
25
+ retry?: boolean | number;
26
+ retryDelay?: ResourceQueryOptions<TData>['retryDelay'];
27
+ refetchInterval?: number | false;
28
+ refetchIntervalInBackground?: boolean;
29
+ placeholderData?: ResourceQueryOptions<TData>['placeholderData'];
30
+ }
31
+
32
+ export function listQuerySettings<TData>(options: ResourceQueryOptions<TData> | undefined): ListQuerySettings<TData> {
33
+ return {
34
+ enabled: options?.enabled ?? true,
35
+ ...definedOptions({
36
+ staleTime: options?.staleTime,
37
+ gcTime: options?.gcTime,
38
+ refetchOnWindowFocus: options?.refetchOnWindowFocus,
39
+ retry: options?.retry,
40
+ retryDelay: options?.retryDelay,
41
+ refetchInterval: options?.refetchInterval,
42
+ refetchIntervalInBackground: options?.refetchIntervalInBackground,
43
+ placeholderData: options?.placeholderData,
44
+ }),
45
+ };
46
+ }
47
+
48
+ export function applyListSelect<TData>(data: TData, select?: (data: TData) => TData): TData {
49
+ return select ? select(data) : data;
50
+ }
@@ -1,6 +1,7 @@
1
1
  import { Type, type Static, type TSchema } from 'typebox';
2
2
  import type { AdminContextAccessor } from './context.svelte';
3
3
  import type { DataProvider, GetListParams, GetOneParams, GetManyParams } from './types';
4
+ import { crudFieldOperatorSchema } from './crud-operator-schema';
4
5
  import { HttpError } from './types';
5
6
  import { contractProvider, type ResourceContract } from './resource-contract';
6
7
  import { definedOptions } from './defined-options';
@@ -12,13 +13,11 @@ const filters = Type.Cyclic({
12
13
  Filters: Type.Union([
13
14
  Type.Object({
14
15
  field: Type.String(),
15
- operator: Type.Union(([
16
- 'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in', 'nin', 'contains', 'ncontains',
17
- 'startswith', 'endswith', 'null', 'nnull', 'between', 'nbetween',
18
- ] as const).map(value => Type.Literal(value))),
16
+ operator: crudFieldOperatorSchema,
19
17
  value: Type.Unknown(),
20
18
  }, { additionalProperties: false }),
21
19
  Type.Object({
20
+ key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
22
21
  operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
23
22
  value: Type.Array(Type.Ref('Filters')),
24
23
  }, { additionalProperties: false }),
@@ -500,6 +500,7 @@ export function validateContractMutationParams(contract: ResourceContract | unde
500
500
  }
501
501
 
502
502
  const filterGroup = Type.Object({
503
+ key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
503
504
  operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
504
505
  value: Type.Array(Type.Unknown()),
505
506
  }, { additionalProperties: false });
@@ -532,10 +533,12 @@ function checkFilters(filters: unknown, record: TObject, depth = 0): void {
532
533
  }
533
534
  const scalar = Type.Exclude(field, Type.Null());
534
535
  switch (filter.operator) {
535
- case 'eq': case 'ne': check(field, filter.value, filter.field); break;
536
- case 'in': case 'nin': check(Type.Array(field), filter.value, filter.field); break;
536
+ case 'eq': case 'ne': case 'eqs': case 'nes': check(field, filter.value, filter.field); break;
537
+ case 'in': case 'nin': case 'ina': case 'nina': check(Type.Array(field), filter.value, filter.field); break;
537
538
  case 'null': case 'nnull': check(Type.Null(), filter.value, filter.field); break;
538
- case 'contains': case 'ncontains': case 'startswith': case 'endswith':
539
+ case 'contains': case 'ncontains': case 'containss': case 'ncontainss':
540
+ case 'startswith': case 'nstartswith': case 'startswiths': case 'nstartswiths':
541
+ case 'endswith': case 'nendswith': case 'endswiths': case 'nendswiths':
539
542
  check(Type.Intersect([scalar, Type.String()]), filter.value, filter.field); break;
540
543
  case 'lt': case 'lte': case 'gt': case 'gte':
541
544
  check(Type.Intersect([scalar, Type.Union([Type.String(), Type.Number()])]), filter.value, filter.field); break;
@@ -11,6 +11,7 @@ import type {
11
11
  ResourceInputOperation,
12
12
  GetOneResult, GetManyResult, GetListResult,
13
13
  } from './types';
14
+ import { crudFieldOperatorSchema } from './crud-operator-schema';
14
15
 
15
16
  export interface ResourceSchemas {
16
17
  /** Schema for complete records returned by standard CRUD operations. */
@@ -46,17 +47,13 @@ const common = {
46
47
  const filter = Type.Cyclic({
47
48
  Filter: Type.Union([
48
49
  Type.Object({
50
+ key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
49
51
  operator: Type.Union([Type.Literal('or'), Type.Literal('and')]),
50
52
  value: Type.Array(Type.Ref('Filter')),
51
53
  }, { additionalProperties: false }),
52
54
  Type.Object({
53
55
  field: Type.String(),
54
- operator: Type.Union([
55
- Type.Literal('eq'), Type.Literal('ne'), Type.Literal('lt'), Type.Literal('gt'),
56
- Type.Literal('lte'), Type.Literal('gte'), Type.Literal('contains'), Type.Literal('ncontains'),
57
- Type.Literal('startswith'), Type.Literal('endswith'), Type.Literal('in'), Type.Literal('nin'),
58
- Type.Literal('null'), Type.Literal('nnull'), Type.Literal('between'), Type.Literal('nbetween'),
59
- ]),
56
+ operator: crudFieldOperatorSchema,
60
57
  value: Type.Unknown(),
61
58
  }, { additionalProperties: false }),
62
59
  ]),
@@ -23,6 +23,17 @@ export interface RouterProvider {
23
23
  };
24
24
  /** Formats an internal path into an href string for <a> tags */
25
25
  formatLink?: (path: string) => string;
26
+ /**
27
+ * Optional path builder. useGetToPath calls this when a router wants to
28
+ * map the default resource path onto its own routes.
29
+ */
30
+ toPath?: (options: {
31
+ resource?: string;
32
+ action?: 'list' | 'create' | 'edit' | 'show' | 'clone';
33
+ id?: string | number;
34
+ meta?: Record<string, unknown>;
35
+ path: string;
36
+ }) => string;
26
37
  }
27
38
 
28
39
  // ─── Hash Router (default) ──────────────────────────────────