@wordrhyme/auto-crud-server 2.1.1 → 2.3.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/README.md CHANGED
@@ -1321,3 +1321,42 @@ Set `counts: true` on `createCrudRouter` to expose `counts({ queries })`. Each q
1321
1321
  This route uses the list procedure, guard, scope, soft deletion and extension conditions. It does not load or enrich rows. Keep the supplied database scoped to the caller. Counts are disabled by default. If list middleware transforms filters or enforces additional visibility restrictions, supply the equivalent transformation through `middleware.counts({ ctx, input, next })` before opting in; row enrichment middleware is deliberately not executed.
1322
1322
 
1323
1323
  The database provider must implement governed `$counts(table, predicates)`, applying the same tenant, row and field observation rules as scalar counts. Missing support returns `PRECONDITION_FAILED`; this route never falls back to raw aggregation or repeated list calls. Deliver the Host capability before enabling counts in consumers, and pin a published Components version containing this route.
1324
+
1325
+ ## 结构化标签条件
1326
+
1327
+ 列表与导出共享标签条件协议:
1328
+
1329
+ ```ts
1330
+ {
1331
+ id: 'tags', variant: 'tags', operator: 'matches', filterId: 'tags',
1332
+ value: { include: ['vip'], exclude: ['blocked'], match: 'any' },
1333
+ }
1334
+ ```
1335
+
1336
+ 固定字段对应动态标签 ID;包含与排除不能有同一个 ID。标签条件内部是 `(任一/全部正选) AND (无反选)`,然后与普通条件按照 `joinOperator` 组合。客户端应删除空标签条件;服务端 provider 应拒绝空条件和不存在的 ID。
1337
+
1338
+ 为 CRUD extension provider 实现 `buildConditions({ id, entityId, filters, joinOperator, search })`,返回 `{ filter?: SQL, search?: SQL }`。这属于可信进程内接口,客户端不能提供 SQL。使用 `entityId` 与标签关联表构造相关 `EXISTS` 查询,列表、总数和导出会在原有数据权限条件内组合这些谓词,无须先取一批实体 ID。
1339
+
1340
+ 扩展筛选统一通过既有 `buildConditions` 接口生成 SQL。标签字段不直接映射为基础表列,应由扩展 provider 提供条件和读取投影;赋值服务负责校验租户、字段及记录更新权限。
1341
+
1342
+ ## 按请求补充查询条件
1343
+
1344
+ `query({ ctx, input, operation })` 在守卫之后执行,`operation` 为 `list` 或 `export`,`input` 来自对应输入 schema 和 middleware。返回的 `where` 始终与普通筛选、搜索、scope 求交集,先于列表与导出总数、分页及导出限制执行。未配置时保持原行为。
1345
+
1346
+ ```ts
1347
+ createCrudRouter({
1348
+ table: products,
1349
+ listInputSchema,
1350
+ exportInputSchema,
1351
+ query: async ({ ctx, input }) => {
1352
+ if (!input.image) return {};
1353
+ const distance = await imageDistance(ctx, input.image);
1354
+ return {
1355
+ where: sql`${distance} <= ${0.65}`,
1356
+ ...(!input.sort?.length ? { orderBy: [asc(distance), asc(products.id)] } : {}),
1357
+ };
1358
+ },
1359
+ });
1360
+ ```
1361
+
1362
+ `orderBy` 提供时替换默认排序;权限和作用域不会被覆盖。SQL 表达式必须通过当前数据库 capability 的治理机制构造,不能把其他租户或无权读取的数据带入派生条件。本扩展只作用于列表及导出;批量 counts 仍使用其原有输入契约。
package/dist/index.cjs CHANGED
@@ -38,6 +38,65 @@ date_fns_endOfDay = __toESM(date_fns_endOfDay);
38
38
  let date_fns_startOfDay = require("date-fns/startOfDay");
39
39
  date_fns_startOfDay = __toESM(date_fns_startOfDay);
40
40
 
41
+ //#region src/lib/import-errors.ts
42
+ const runtime = zod.z;
43
+ const PARAMS = [
44
+ "values",
45
+ "options",
46
+ "expected",
47
+ "origin",
48
+ "type",
49
+ "minimum",
50
+ "maximum",
51
+ "inclusive",
52
+ "exact",
53
+ "format",
54
+ "validation",
55
+ "pattern",
56
+ "prefix",
57
+ "suffix",
58
+ "includes",
59
+ "divisor",
60
+ "multipleOf",
61
+ "keys"
62
+ ];
63
+ function importIssue(issue, row) {
64
+ const detail = issue;
65
+ const input = Object.hasOwn(detail, "input") ? detail["input"] : issue.path.reduce((value, key) => value != null && typeof value === "object" ? value[key] : void 0, row);
66
+ const defaultError = (runtime.config?.().localeError ?? runtime.defaultErrorMap)?.({
67
+ ...detail,
68
+ input
69
+ }, {
70
+ data: input,
71
+ defaultError: ""
72
+ });
73
+ const defaultMessage = typeof defaultError === "string" ? defaultError : defaultError?.message;
74
+ if (issue.code === "custom" || detail["exact"] === true || issue.message !== defaultMessage) return null;
75
+ const params = Object.fromEntries(PARAMS.filter((key) => detail[key] !== void 0).map((key) => [key, typeof detail[key] === "bigint" ? String(detail[key]) : detail[key]]));
76
+ if (issue.code === "invalid_type") params["received"] = typeof detail["received"] === "string" ? detail["received"] : input === null ? "null" : Array.isArray(input) ? "array" : typeof input === "number" && Number.isNaN(input) ? "nan" : typeof input;
77
+ let code = issue.code;
78
+ if (code === "invalid_enum_value") {
79
+ code = "invalid_value";
80
+ params["values"] = params["options"];
81
+ } else if (code === "invalid_literal") {
82
+ code = "invalid_value";
83
+ params["values"] = [params["expected"]];
84
+ } else if (code === "invalid_string") {
85
+ if (typeof params["validation"] !== "string" || params["validation"] === "regex") return null;
86
+ code = "invalid_format";
87
+ params["format"] = params["validation"];
88
+ }
89
+ if (params["type"] !== void 0) params["origin"] = params["type"];
90
+ if (params["multipleOf"] !== void 0) params["divisor"] = params["multipleOf"];
91
+ return {
92
+ code,
93
+ path: issue.path.map(String),
94
+ message: issue.message,
95
+ params
96
+ };
97
+ }
98
+
99
+ //#endregion
41
100
  //#region src/trpc.ts
42
101
  const t = __trpc_server.initTRPC.context().create({ transformer: superjson.default });
43
102
  const router = t.router;
@@ -155,6 +214,7 @@ function resolvedDateCondition(expr, operator, range) {
155
214
  function filterColumns({ table, filters, joinOperator, resolveColumn, resolveDateRange }) {
156
215
  const joinFn = joinOperator === "and" ? drizzle_orm.and : drizzle_orm.or;
157
216
  const validConditions = filters.map((filter) => {
217
+ if (filter.variant === "tags") throw new Error("Tag filters require an extension buildConditions provider");
158
218
  const column = resolveColumn ? resolveColumn(filter.id) : getColumn(table, filter.id);
159
219
  if (!column) return void 0;
160
220
  const expr = column;
@@ -470,7 +530,8 @@ const dataTableConfig = {
470
530
  "dateRange",
471
531
  "boolean",
472
532
  "select",
473
- "multiSelect"
533
+ "multiSelect",
534
+ "tags"
474
535
  ],
475
536
  operators: [
476
537
  "iLike",
@@ -486,7 +547,8 @@ const dataTableConfig = {
486
547
  "gt",
487
548
  "gte",
488
549
  "isBetween",
489
- "isRelativeToToday"
550
+ "isRelativeToToday",
551
+ "matches"
490
552
  ],
491
553
  joinOperators: ["and", "or"]
492
554
  };
@@ -602,13 +664,25 @@ function resolveConfig(config) {
602
664
  function resolveMetaProcedure(config, fallback) {
603
665
  return isProcedureMap(config) ? config.meta ?? fallback : fallback;
604
666
  }
605
- const filterItemSchema = zod.z.object({
667
+ const tagFilterValueSchema = zod.z.object({
668
+ include: zod.z.array(zod.z.string().min(1)).max(100),
669
+ exclude: zod.z.array(zod.z.string().min(1)).max(100),
670
+ match: zod.z.enum(["any", "all"])
671
+ }).strict().refine(({ include, exclude }) => !include.some((id) => exclude.includes(id)), "A tag cannot be both included and excluded");
672
+ const ordinaryFilterSchema = zod.z.object({
606
673
  id: zod.z.string(),
607
674
  value: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]),
608
- variant: zod.z.enum(dataTableConfig.filterVariants),
609
- operator: zod.z.enum(dataTableConfig.operators),
675
+ variant: zod.z.enum(dataTableConfig.filterVariants.filter((variant) => variant !== "tags")),
676
+ operator: zod.z.enum(dataTableConfig.operators.filter((operator) => operator !== "matches")),
610
677
  filterId: zod.z.string()
611
678
  });
679
+ const filterItemSchema = zod.z.union([ordinaryFilterSchema, zod.z.object({
680
+ id: zod.z.string(),
681
+ filterId: zod.z.string(),
682
+ variant: zod.z.literal("tags"),
683
+ operator: zod.z.literal("matches"),
684
+ value: tagFilterValueSchema
685
+ })]);
612
686
  const baseListInputSchema = zod.z.object({
613
687
  page: zod.z.number().min(1).default(1),
614
688
  perPage: zod.z.number().min(1).max(100).default(10),
@@ -1250,7 +1324,13 @@ function createCrudRouter(config) {
1250
1324
  skipped: zod.z.number(),
1251
1325
  failed: zod.z.array(zod.z.object({
1252
1326
  row: zod.z.number(),
1253
- errors: zod.z.array(zod.z.string())
1327
+ errors: zod.z.array(zod.z.string()),
1328
+ issues: zod.z.array(zod.z.object({
1329
+ code: zod.z.string(),
1330
+ path: zod.z.array(zod.z.string()),
1331
+ message: zod.z.string(),
1332
+ params: zod.z.record(zod.z.string(), zod.z.unknown())
1333
+ }).nullable()).optional()
1254
1334
  }))
1255
1335
  });
1256
1336
  const resolved = resolveConfig(config);
@@ -1409,11 +1489,17 @@ function createCrudRouter(config) {
1409
1489
  list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
1410
1490
  await withGuard(ctx, "list");
1411
1491
  const doList = async (listInput$1) => {
1412
- const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
1492
+ const extra = await config.query?.({
1493
+ ctx,
1494
+ input: listInput$1,
1495
+ operation: "list"
1496
+ });
1497
+ const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput$1);
1498
+ const where = combineConditions(baseWhere, extra?.where);
1413
1499
  const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
1414
1500
  let query = ctx.db.select().from(table).$dynamic();
1415
1501
  if (where) query = query.where(where);
1416
- const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
1502
+ const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
1417
1503
  if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
1418
1504
  let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
1419
1505
  if (where) countQuery = countQuery.where(where);
@@ -1698,6 +1784,11 @@ function createCrudRouter(config) {
1698
1784
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1699
1785
  await withGuard(ctx, "export");
1700
1786
  const doExport = async (exportInput$1) => {
1787
+ const extra = await config.query?.({
1788
+ ctx,
1789
+ input: exportInput$1,
1790
+ operation: "export"
1791
+ });
1701
1792
  const columns = await querySearch(ctx, exportInput$1.search);
1702
1793
  const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1703
1794
  page: 1,
@@ -1723,10 +1814,10 @@ function createCrudRouter(config) {
1723
1814
  resolveDateRange: ctx.resolveDateRange
1724
1815
  }) : void 0;
1725
1816
  const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1726
- const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1817
+ const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition, extra?.where));
1727
1818
  let query = ctx.db.select().from(table).$dynamic();
1728
1819
  if (where) query = query.where(where);
1729
- const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, false);
1820
+ const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, false);
1730
1821
  if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
1731
1822
  let countQuery = ctx.db.select({ count: drizzle_orm.sql`count(*)::int` }).from(table).$dynamic();
1732
1823
  if (where) countQuery = countQuery.where(where);
@@ -1783,7 +1874,7 @@ function createCrudRouter(config) {
1783
1874
  const failed = [];
1784
1875
  for (let i = 0; i < importData$1.rows.length; i++) {
1785
1876
  const row = importData$1.rows[i];
1786
- const result = importSchema.safeParse(row);
1877
+ const result = importSchema.safeParse(row, { reportInput: true });
1787
1878
  if (result.success) {
1788
1879
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1789
1880
  validRows.push(splitRow);
@@ -1791,7 +1882,8 @@ function createCrudRouter(config) {
1791
1882
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1792
1883
  failed.push({
1793
1884
  row: i,
1794
- errors
1885
+ errors,
1886
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1795
1887
  });
1796
1888
  if (importData$1.onConflict === "error") return {
1797
1889
  success: 0,
@@ -1943,4 +2035,5 @@ exports.beforeMiddleware = beforeMiddleware;
1943
2035
  exports.composeMiddleware = composeMiddleware;
1944
2036
  exports.createCrudRouter = createCrudRouter;
1945
2037
  exports.publicProcedure = publicProcedure;
1946
- exports.router = router;
2038
+ exports.router = router;
2039
+ exports.tagFilterValueSchema = tagFilterValueSchema;
package/dist/index.d.cts CHANGED
@@ -6,9 +6,9 @@ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
6
6
 
7
7
  //#region src/lib/filter-columns.d.ts
8
8
  /** 过滤器变体类型 */
9
- type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect';
9
+ type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect' | 'tags';
10
10
  /** 过滤器操作符 */
11
- type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty';
11
+ type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty' | 'matches';
12
12
  /** 扩展的列过滤器 */
13
13
  interface ExtendedColumnFilter<T extends Table = Table> {
14
14
  id: keyof T | string;
@@ -139,7 +139,11 @@ interface ListInput {
139
139
  search?: string;
140
140
  filters?: Array<{
141
141
  id: string;
142
- value: string | string[];
142
+ value: string | string[] | {
143
+ include: string[];
144
+ exclude: string[];
145
+ match: 'any' | 'all';
146
+ };
143
147
  variant: string;
144
148
  operator: string;
145
149
  filterId: string;
@@ -183,7 +187,11 @@ interface ExportInput {
183
187
  search?: string;
184
188
  filters?: Array<{
185
189
  id: string;
186
- value: string | string[];
190
+ value: string | string[] | {
191
+ include: string[];
192
+ exclude: string[];
193
+ match: 'any' | 'all';
194
+ };
187
195
  variant: string;
188
196
  operator: string;
189
197
  filterId: string;
@@ -201,7 +209,11 @@ interface CrudExtensionMetadata {
201
209
  }
202
210
  interface CrudExtensionFilter {
203
211
  id: string;
204
- value: string | string[];
212
+ value: string | string[] | {
213
+ include: string[];
214
+ exclude: string[];
215
+ match: 'any' | 'all';
216
+ };
205
217
  variant: string;
206
218
  operator: string;
207
219
  filterId?: string | undefined;
@@ -293,11 +305,20 @@ interface ExportResult<TSelect> {
293
305
  /**
294
306
  * 导入行失败详情
295
307
  */
308
+ /** Serializable validation details; excludes the submitted cell value. */
309
+ interface ImportIssue {
310
+ code: string;
311
+ path: string[];
312
+ message: string;
313
+ params: Record<string, unknown>;
314
+ }
296
315
  interface ImportFailedRow {
297
316
  /** 行号(0-indexed) */
298
317
  row: number;
299
318
  /** 验证错误信息列表 */
300
319
  errors: string[];
320
+ /** Optional details for localized presentation; errors remains backwards compatible. */
321
+ issues?: Array<ImportIssue | null>;
301
322
  }
302
323
  /**
303
324
  * 导入结果类型
@@ -654,6 +675,20 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
654
675
  * - 默认查询逻辑只读取基础字段,额外字段会保留给 middleware.export 使用
655
676
  */
656
677
  exportInputSchema?: z.ZodType<TExportInput>;
678
+ /** Additional request conditions, ANDed before count/pagination/export limits.
679
+ * orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
680
+ */
681
+ query?: (params: {
682
+ ctx: TContext;
683
+ input: TListInput | TExportInput;
684
+ operation: 'list' | 'export';
685
+ }) => {
686
+ where?: SQL;
687
+ orderBy?: SQL[];
688
+ } | Promise<{
689
+ where?: SQL;
690
+ orderBy?: SQL[];
691
+ }>;
657
692
  /**
658
693
  * Procedure 配置(统一字段)
659
694
  *
@@ -843,6 +878,14 @@ interface CrudProcedures {
843
878
  type CrudRouterReturn = ReturnType<typeof router> & {
844
879
  procedures: CrudProcedures;
845
880
  };
881
+ declare const tagFilterValueSchema: z.ZodObject<{
882
+ include: z.ZodArray<z.ZodString>;
883
+ exclude: z.ZodArray<z.ZodString>;
884
+ match: z.ZodEnum<{
885
+ any: "any";
886
+ all: "all";
887
+ }>;
888
+ }, z.core.$strict>;
846
889
  declare const baseListInputSchema: z.ZodObject<{
847
890
  page: z.ZodDefault<z.ZodNumber>;
848
891
  perPage: z.ZodDefault<z.ZodNumber>;
@@ -851,7 +894,7 @@ declare const baseListInputSchema: z.ZodObject<{
851
894
  desc: z.ZodBoolean;
852
895
  }, z.core.$strip>>>;
853
896
  search: z.ZodOptional<z.ZodString>;
854
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
897
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
855
898
  id: z.ZodString;
856
899
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
857
900
  variant: z.ZodEnum<{
@@ -881,7 +924,20 @@ declare const baseListInputSchema: z.ZodObject<{
881
924
  notInArray: "notInArray";
882
925
  }>;
883
926
  filterId: z.ZodString;
884
- }, z.core.$strip>>>;
927
+ }, z.core.$strip>, z.ZodObject<{
928
+ id: z.ZodString;
929
+ filterId: z.ZodString;
930
+ variant: z.ZodLiteral<"tags">;
931
+ operator: z.ZodLiteral<"matches">;
932
+ value: z.ZodObject<{
933
+ include: z.ZodArray<z.ZodString>;
934
+ exclude: z.ZodArray<z.ZodString>;
935
+ match: z.ZodEnum<{
936
+ any: "any";
937
+ all: "all";
938
+ }>;
939
+ }, z.core.$strict>;
940
+ }, z.core.$strip>]>>>;
885
941
  joinOperator: z.ZodDefault<z.ZodEnum<{
886
942
  and: "and";
887
943
  or: "or";
@@ -896,7 +952,7 @@ declare const baseExportInputSchema: z.ZodObject<{
896
952
  desc: z.ZodBoolean;
897
953
  }, z.core.$strip>>>;
898
954
  search: z.ZodOptional<z.ZodString>;
899
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
955
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
900
956
  id: z.ZodString;
901
957
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
902
958
  variant: z.ZodEnum<{
@@ -926,7 +982,20 @@ declare const baseExportInputSchema: z.ZodObject<{
926
982
  notInArray: "notInArray";
927
983
  }>;
928
984
  filterId: z.ZodString;
929
- }, z.core.$strip>>>;
985
+ }, z.core.$strip>, z.ZodObject<{
986
+ id: z.ZodString;
987
+ filterId: z.ZodString;
988
+ variant: z.ZodLiteral<"tags">;
989
+ operator: z.ZodLiteral<"matches">;
990
+ value: z.ZodObject<{
991
+ include: z.ZodArray<z.ZodString>;
992
+ exclude: z.ZodArray<z.ZodString>;
993
+ match: z.ZodEnum<{
994
+ any: "any";
995
+ all: "all";
996
+ }>;
997
+ }, z.core.$strict>;
998
+ }, z.core.$strip>]>>>;
930
999
  joinOperator: z.ZodDefault<z.ZodEnum<{
931
1000
  and: "and";
932
1001
  or: "or";
@@ -936,7 +1005,7 @@ declare const baseExportInputSchema: z.ZodObject<{
936
1005
  declare const baseCountsInputSchema: z.ZodObject<{
937
1006
  queries: z.ZodArray<z.ZodObject<{
938
1007
  search: z.ZodOptional<z.ZodString>;
939
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
1008
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
940
1009
  id: z.ZodString;
941
1010
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
942
1011
  variant: z.ZodEnum<{
@@ -966,7 +1035,20 @@ declare const baseCountsInputSchema: z.ZodObject<{
966
1035
  notInArray: "notInArray";
967
1036
  }>;
968
1037
  filterId: z.ZodString;
969
- }, z.core.$strip>>>;
1038
+ }, z.core.$strip>, z.ZodObject<{
1039
+ id: z.ZodString;
1040
+ filterId: z.ZodString;
1041
+ variant: z.ZodLiteral<"tags">;
1042
+ operator: z.ZodLiteral<"matches">;
1043
+ value: z.ZodObject<{
1044
+ include: z.ZodArray<z.ZodString>;
1045
+ exclude: z.ZodArray<z.ZodString>;
1046
+ match: z.ZodEnum<{
1047
+ any: "any";
1048
+ all: "all";
1049
+ }>;
1050
+ }, z.core.$strict>;
1051
+ }, z.core.$strip>]>>>;
970
1052
  joinOperator: z.ZodDefault<z.ZodEnum<{
971
1053
  and: "and";
972
1054
  or: "or";
@@ -1087,4 +1169,4 @@ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1087
1169
  }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
1088
1170
  type AppRouter = typeof appRouter;
1089
1171
  //#endregion
1090
- export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1172
+ export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportIssue, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
package/dist/index.d.ts CHANGED
@@ -7,9 +7,9 @@ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
7
7
 
8
8
  //#region src/lib/filter-columns.d.ts
9
9
  /** 过滤器变体类型 */
10
- type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect';
10
+ type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect' | 'tags';
11
11
  /** 过滤器操作符 */
12
- type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty';
12
+ type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty' | 'matches';
13
13
  /** 扩展的列过滤器 */
14
14
  interface ExtendedColumnFilter<T extends Table = Table> {
15
15
  id: keyof T | string;
@@ -140,7 +140,11 @@ interface ListInput {
140
140
  search?: string;
141
141
  filters?: Array<{
142
142
  id: string;
143
- value: string | string[];
143
+ value: string | string[] | {
144
+ include: string[];
145
+ exclude: string[];
146
+ match: 'any' | 'all';
147
+ };
144
148
  variant: string;
145
149
  operator: string;
146
150
  filterId: string;
@@ -184,7 +188,11 @@ interface ExportInput {
184
188
  search?: string;
185
189
  filters?: Array<{
186
190
  id: string;
187
- value: string | string[];
191
+ value: string | string[] | {
192
+ include: string[];
193
+ exclude: string[];
194
+ match: 'any' | 'all';
195
+ };
188
196
  variant: string;
189
197
  operator: string;
190
198
  filterId: string;
@@ -202,7 +210,11 @@ interface CrudExtensionMetadata {
202
210
  }
203
211
  interface CrudExtensionFilter {
204
212
  id: string;
205
- value: string | string[];
213
+ value: string | string[] | {
214
+ include: string[];
215
+ exclude: string[];
216
+ match: 'any' | 'all';
217
+ };
206
218
  variant: string;
207
219
  operator: string;
208
220
  filterId?: string | undefined;
@@ -294,11 +306,20 @@ interface ExportResult<TSelect> {
294
306
  /**
295
307
  * 导入行失败详情
296
308
  */
309
+ /** Serializable validation details; excludes the submitted cell value. */
310
+ interface ImportIssue {
311
+ code: string;
312
+ path: string[];
313
+ message: string;
314
+ params: Record<string, unknown>;
315
+ }
297
316
  interface ImportFailedRow {
298
317
  /** 行号(0-indexed) */
299
318
  row: number;
300
319
  /** 验证错误信息列表 */
301
320
  errors: string[];
321
+ /** Optional details for localized presentation; errors remains backwards compatible. */
322
+ issues?: Array<ImportIssue | null>;
302
323
  }
303
324
  /**
304
325
  * 导入结果类型
@@ -655,6 +676,20 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
655
676
  * - 默认查询逻辑只读取基础字段,额外字段会保留给 middleware.export 使用
656
677
  */
657
678
  exportInputSchema?: z.ZodType<TExportInput>;
679
+ /** Additional request conditions, ANDed before count/pagination/export limits.
680
+ * orderBy, when provided, replaces the normal ordering. Scope and guards still apply.
681
+ */
682
+ query?: (params: {
683
+ ctx: TContext;
684
+ input: TListInput | TExportInput;
685
+ operation: 'list' | 'export';
686
+ }) => {
687
+ where?: SQL;
688
+ orderBy?: SQL[];
689
+ } | Promise<{
690
+ where?: SQL;
691
+ orderBy?: SQL[];
692
+ }>;
658
693
  /**
659
694
  * Procedure 配置(统一字段)
660
695
  *
@@ -844,6 +879,14 @@ interface CrudProcedures {
844
879
  type CrudRouterReturn = ReturnType<typeof router> & {
845
880
  procedures: CrudProcedures;
846
881
  };
882
+ declare const tagFilterValueSchema: z.ZodObject<{
883
+ include: z.ZodArray<z.ZodString>;
884
+ exclude: z.ZodArray<z.ZodString>;
885
+ match: z.ZodEnum<{
886
+ any: "any";
887
+ all: "all";
888
+ }>;
889
+ }, z.core.$strict>;
847
890
  declare const baseListInputSchema: z.ZodObject<{
848
891
  page: z.ZodDefault<z.ZodNumber>;
849
892
  perPage: z.ZodDefault<z.ZodNumber>;
@@ -852,7 +895,7 @@ declare const baseListInputSchema: z.ZodObject<{
852
895
  desc: z.ZodBoolean;
853
896
  }, z.core.$strip>>>;
854
897
  search: z.ZodOptional<z.ZodString>;
855
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
898
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
856
899
  id: z.ZodString;
857
900
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
858
901
  variant: z.ZodEnum<{
@@ -882,7 +925,20 @@ declare const baseListInputSchema: z.ZodObject<{
882
925
  notInArray: "notInArray";
883
926
  }>;
884
927
  filterId: z.ZodString;
885
- }, z.core.$strip>>>;
928
+ }, z.core.$strip>, z.ZodObject<{
929
+ id: z.ZodString;
930
+ filterId: z.ZodString;
931
+ variant: z.ZodLiteral<"tags">;
932
+ operator: z.ZodLiteral<"matches">;
933
+ value: z.ZodObject<{
934
+ include: z.ZodArray<z.ZodString>;
935
+ exclude: z.ZodArray<z.ZodString>;
936
+ match: z.ZodEnum<{
937
+ any: "any";
938
+ all: "all";
939
+ }>;
940
+ }, z.core.$strict>;
941
+ }, z.core.$strip>]>>>;
886
942
  joinOperator: z.ZodDefault<z.ZodEnum<{
887
943
  and: "and";
888
944
  or: "or";
@@ -897,7 +953,7 @@ declare const baseExportInputSchema: z.ZodObject<{
897
953
  desc: z.ZodBoolean;
898
954
  }, z.core.$strip>>>;
899
955
  search: z.ZodOptional<z.ZodString>;
900
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
956
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
901
957
  id: z.ZodString;
902
958
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
903
959
  variant: z.ZodEnum<{
@@ -927,7 +983,20 @@ declare const baseExportInputSchema: z.ZodObject<{
927
983
  notInArray: "notInArray";
928
984
  }>;
929
985
  filterId: z.ZodString;
930
- }, z.core.$strip>>>;
986
+ }, z.core.$strip>, z.ZodObject<{
987
+ id: z.ZodString;
988
+ filterId: z.ZodString;
989
+ variant: z.ZodLiteral<"tags">;
990
+ operator: z.ZodLiteral<"matches">;
991
+ value: z.ZodObject<{
992
+ include: z.ZodArray<z.ZodString>;
993
+ exclude: z.ZodArray<z.ZodString>;
994
+ match: z.ZodEnum<{
995
+ any: "any";
996
+ all: "all";
997
+ }>;
998
+ }, z.core.$strict>;
999
+ }, z.core.$strip>]>>>;
931
1000
  joinOperator: z.ZodDefault<z.ZodEnum<{
932
1001
  and: "and";
933
1002
  or: "or";
@@ -937,7 +1006,7 @@ declare const baseExportInputSchema: z.ZodObject<{
937
1006
  declare const baseCountsInputSchema: z.ZodObject<{
938
1007
  queries: z.ZodArray<z.ZodObject<{
939
1008
  search: z.ZodOptional<z.ZodString>;
940
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
1009
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
941
1010
  id: z.ZodString;
942
1011
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
943
1012
  variant: z.ZodEnum<{
@@ -967,7 +1036,20 @@ declare const baseCountsInputSchema: z.ZodObject<{
967
1036
  notInArray: "notInArray";
968
1037
  }>;
969
1038
  filterId: z.ZodString;
970
- }, z.core.$strip>>>;
1039
+ }, z.core.$strip>, z.ZodObject<{
1040
+ id: z.ZodString;
1041
+ filterId: z.ZodString;
1042
+ variant: z.ZodLiteral<"tags">;
1043
+ operator: z.ZodLiteral<"matches">;
1044
+ value: z.ZodObject<{
1045
+ include: z.ZodArray<z.ZodString>;
1046
+ exclude: z.ZodArray<z.ZodString>;
1047
+ match: z.ZodEnum<{
1048
+ any: "any";
1049
+ all: "all";
1050
+ }>;
1051
+ }, z.core.$strict>;
1052
+ }, z.core.$strip>]>>>;
971
1053
  joinOperator: z.ZodDefault<z.ZodEnum<{
972
1054
  and: "and";
973
1055
  or: "or";
@@ -1088,4 +1170,4 @@ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1088
1170
  }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
1089
1171
  type AppRouter = typeof appRouter;
1090
1172
  //#endregion
1091
- export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1173
+ export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportIssue, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
package/dist/index.js CHANGED
@@ -7,6 +7,65 @@ import { addDays } from "date-fns/addDays";
7
7
  import { endOfDay } from "date-fns/endOfDay";
8
8
  import { startOfDay } from "date-fns/startOfDay";
9
9
 
10
+ //#region src/lib/import-errors.ts
11
+ const runtime = z;
12
+ const PARAMS = [
13
+ "values",
14
+ "options",
15
+ "expected",
16
+ "origin",
17
+ "type",
18
+ "minimum",
19
+ "maximum",
20
+ "inclusive",
21
+ "exact",
22
+ "format",
23
+ "validation",
24
+ "pattern",
25
+ "prefix",
26
+ "suffix",
27
+ "includes",
28
+ "divisor",
29
+ "multipleOf",
30
+ "keys"
31
+ ];
32
+ function importIssue(issue, row) {
33
+ const detail = issue;
34
+ const input = Object.hasOwn(detail, "input") ? detail["input"] : issue.path.reduce((value, key) => value != null && typeof value === "object" ? value[key] : void 0, row);
35
+ const defaultError = (runtime.config?.().localeError ?? runtime.defaultErrorMap)?.({
36
+ ...detail,
37
+ input
38
+ }, {
39
+ data: input,
40
+ defaultError: ""
41
+ });
42
+ const defaultMessage = typeof defaultError === "string" ? defaultError : defaultError?.message;
43
+ if (issue.code === "custom" || detail["exact"] === true || issue.message !== defaultMessage) return null;
44
+ const params = Object.fromEntries(PARAMS.filter((key) => detail[key] !== void 0).map((key) => [key, typeof detail[key] === "bigint" ? String(detail[key]) : detail[key]]));
45
+ if (issue.code === "invalid_type") params["received"] = typeof detail["received"] === "string" ? detail["received"] : input === null ? "null" : Array.isArray(input) ? "array" : typeof input === "number" && Number.isNaN(input) ? "nan" : typeof input;
46
+ let code = issue.code;
47
+ if (code === "invalid_enum_value") {
48
+ code = "invalid_value";
49
+ params["values"] = params["options"];
50
+ } else if (code === "invalid_literal") {
51
+ code = "invalid_value";
52
+ params["values"] = [params["expected"]];
53
+ } else if (code === "invalid_string") {
54
+ if (typeof params["validation"] !== "string" || params["validation"] === "regex") return null;
55
+ code = "invalid_format";
56
+ params["format"] = params["validation"];
57
+ }
58
+ if (params["type"] !== void 0) params["origin"] = params["type"];
59
+ if (params["multipleOf"] !== void 0) params["divisor"] = params["multipleOf"];
60
+ return {
61
+ code,
62
+ path: issue.path.map(String),
63
+ message: issue.message,
64
+ params
65
+ };
66
+ }
67
+
68
+ //#endregion
10
69
  //#region src/trpc.ts
11
70
  const t = initTRPC.context().create({ transformer: superjson });
12
71
  const router = t.router;
@@ -124,6 +183,7 @@ function resolvedDateCondition(expr, operator, range) {
124
183
  function filterColumns({ table, filters, joinOperator, resolveColumn, resolveDateRange }) {
125
184
  const joinFn = joinOperator === "and" ? and : or;
126
185
  const validConditions = filters.map((filter) => {
186
+ if (filter.variant === "tags") throw new Error("Tag filters require an extension buildConditions provider");
127
187
  const column = resolveColumn ? resolveColumn(filter.id) : getColumn(table, filter.id);
128
188
  if (!column) return void 0;
129
189
  const expr = column;
@@ -439,7 +499,8 @@ const dataTableConfig = {
439
499
  "dateRange",
440
500
  "boolean",
441
501
  "select",
442
- "multiSelect"
502
+ "multiSelect",
503
+ "tags"
443
504
  ],
444
505
  operators: [
445
506
  "iLike",
@@ -455,7 +516,8 @@ const dataTableConfig = {
455
516
  "gt",
456
517
  "gte",
457
518
  "isBetween",
458
- "isRelativeToToday"
519
+ "isRelativeToToday",
520
+ "matches"
459
521
  ],
460
522
  joinOperators: ["and", "or"]
461
523
  };
@@ -571,13 +633,25 @@ function resolveConfig(config) {
571
633
  function resolveMetaProcedure(config, fallback) {
572
634
  return isProcedureMap(config) ? config.meta ?? fallback : fallback;
573
635
  }
574
- const filterItemSchema = z.object({
636
+ const tagFilterValueSchema = z.object({
637
+ include: z.array(z.string().min(1)).max(100),
638
+ exclude: z.array(z.string().min(1)).max(100),
639
+ match: z.enum(["any", "all"])
640
+ }).strict().refine(({ include, exclude }) => !include.some((id) => exclude.includes(id)), "A tag cannot be both included and excluded");
641
+ const ordinaryFilterSchema = z.object({
575
642
  id: z.string(),
576
643
  value: z.union([z.string(), z.array(z.string())]),
577
- variant: z.enum(dataTableConfig.filterVariants),
578
- operator: z.enum(dataTableConfig.operators),
644
+ variant: z.enum(dataTableConfig.filterVariants.filter((variant) => variant !== "tags")),
645
+ operator: z.enum(dataTableConfig.operators.filter((operator) => operator !== "matches")),
579
646
  filterId: z.string()
580
647
  });
648
+ const filterItemSchema = z.union([ordinaryFilterSchema, z.object({
649
+ id: z.string(),
650
+ filterId: z.string(),
651
+ variant: z.literal("tags"),
652
+ operator: z.literal("matches"),
653
+ value: tagFilterValueSchema
654
+ })]);
581
655
  const baseListInputSchema = z.object({
582
656
  page: z.number().min(1).default(1),
583
657
  perPage: z.number().min(1).max(100).default(10),
@@ -1219,7 +1293,13 @@ function createCrudRouter(config) {
1219
1293
  skipped: z.number(),
1220
1294
  failed: z.array(z.object({
1221
1295
  row: z.number(),
1222
- errors: z.array(z.string())
1296
+ errors: z.array(z.string()),
1297
+ issues: z.array(z.object({
1298
+ code: z.string(),
1299
+ path: z.array(z.string()),
1300
+ message: z.string(),
1301
+ params: z.record(z.string(), z.unknown())
1302
+ }).nullable()).optional()
1223
1303
  }))
1224
1304
  });
1225
1305
  const resolved = resolveConfig(config);
@@ -1378,11 +1458,17 @@ function createCrudRouter(config) {
1378
1458
  list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
1379
1459
  await withGuard(ctx, "list");
1380
1460
  const doList = async (listInput$1) => {
1381
- const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
1461
+ const extra = await config.query?.({
1462
+ ctx,
1463
+ input: listInput$1,
1464
+ operation: "list"
1465
+ });
1466
+ const { effectiveInput, where: baseWhere } = await queryWhere(ctx, listInput$1);
1467
+ const where = combineConditions(baseWhere, extra?.where);
1382
1468
  const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
1383
1469
  let query = ctx.db.select().from(table).$dynamic();
1384
1470
  if (where) query = query.where(where);
1385
- const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
1471
+ const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, true);
1386
1472
  if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
1387
1473
  let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
1388
1474
  if (where) countQuery = countQuery.where(where);
@@ -1667,6 +1753,11 @@ function createCrudRouter(config) {
1667
1753
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1668
1754
  await withGuard(ctx, "export");
1669
1755
  const doExport = async (exportInput$1) => {
1756
+ const extra = await config.query?.({
1757
+ ctx,
1758
+ input: exportInput$1,
1759
+ operation: "export"
1760
+ });
1670
1761
  const columns = await querySearch(ctx, exportInput$1.search);
1671
1762
  const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1672
1763
  page: 1,
@@ -1692,10 +1783,10 @@ function createCrudRouter(config) {
1692
1783
  resolveDateRange: ctx.resolveDateRange
1693
1784
  }) : void 0;
1694
1785
  const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1695
- const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1786
+ const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition, extra?.where));
1696
1787
  let query = ctx.db.select().from(table).$dynamic();
1697
1788
  if (where) query = query.where(where);
1698
- const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, false);
1789
+ const orderByExpressions = extra?.orderBy ?? buildOrderByExpressions(effectiveInput.sort, false);
1699
1790
  if (orderByExpressions.length > 0) query = query.orderBy(...orderByExpressions);
1700
1791
  let countQuery = ctx.db.select({ count: sql`count(*)::int` }).from(table).$dynamic();
1701
1792
  if (where) countQuery = countQuery.where(where);
@@ -1752,7 +1843,7 @@ function createCrudRouter(config) {
1752
1843
  const failed = [];
1753
1844
  for (let i = 0; i < importData$1.rows.length; i++) {
1754
1845
  const row = importData$1.rows[i];
1755
- const result = importSchema.safeParse(row);
1846
+ const result = importSchema.safeParse(row, { reportInput: true });
1756
1847
  if (result.success) {
1757
1848
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1758
1849
  validRows.push(splitRow);
@@ -1760,7 +1851,8 @@ function createCrudRouter(config) {
1760
1851
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1761
1852
  failed.push({
1762
1853
  row: i,
1763
- errors
1854
+ errors,
1855
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1764
1856
  });
1765
1857
  if (importData$1.onConflict === "error") return {
1766
1858
  success: 0,
@@ -1902,4 +1994,4 @@ function composeMiddleware(...middlewares) {
1902
1994
  const appRouter = router({});
1903
1995
 
1904
1996
  //#endregion
1905
- export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1997
+ export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wordrhyme/auto-crud-server",
3
3
  "type": "module",
4
- "version": "2.1.1",
4
+ "version": "2.3.0",
5
5
  "description": "tRPC server utilities for auto-crud - automatic CRUD routers for Drizzle ORM",
6
6
  "author": "wordrhyme",
7
7
  "license": "MIT",
@@ -49,8 +49,8 @@
49
49
  "vitest": "^4.0.18",
50
50
  "zod": "^4.3.6",
51
51
  "@internal/eslint-config": "0.3.0",
52
- "@internal/tsconfig": "0.1.0",
53
52
  "@internal/prettier-config": "0.0.1",
53
+ "@internal/tsconfig": "0.1.0",
54
54
  "@internal/tsdown-config": "0.1.0",
55
55
  "@internal/vitest-config": "0.1.0"
56
56
  },