@stacksjs/defaults 0.75.571 → 0.75.573

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.
Files changed (63) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-browse/scripts/chrome.ts +107 -4
  3. package/ai/skills/stacks-cms/SKILL.md +1 -1
  4. package/ai/skills/stacks-dashboard/SKILL.md +283 -12
  5. package/ai/skills/stacks-database/SKILL.md +3 -1
  6. package/ai/skills/stacks-native/CATALOG.md +2 -2
  7. package/ai/skills/stacks-orm/SKILL.md +5 -1
  8. package/ai/skills/stacks-testing/SKILL.md +11 -1
  9. package/app/Actions/Dashboard/Content/CommentUpdateAction.ts +1 -1
  10. package/app/Actions/Dashboard/Content/PostStoreAction.ts +1 -1
  11. package/app/Actions/Dashboard/Content/PostUpdateAction.ts +1 -1
  12. package/app/Actions/Dashboard/Marketing/marketing-list-records.test.ts +2 -2
  13. package/app/Actions/Dashboard/Marketing/marketing-list-records.ts +4 -4
  14. package/app/Actions/Dashboard/Models/ModelShowAction.ts +42 -43
  15. package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +17 -3
  16. package/app/Actions/Dashboard/Models/model-filters.ts +429 -0
  17. package/app/Actions/Dashboard/Models/model-switches.ts +159 -0
  18. package/app/Actions/Dashboard/Models/model-write.ts +6 -0
  19. package/app/Models/Comment.ts +3 -3
  20. package/app/Models/Content/Post.ts +3 -3
  21. package/app/Models/EmailList.ts +8 -6
  22. package/app/Models/Subscriber.ts +2 -0
  23. package/app/Models/Team.ts +2 -0
  24. package/app/Models/User.ts +3 -0
  25. package/functions/dashboard-model-filters.ts +219 -0
  26. package/functions/dashboard-model-record.ts +42 -8
  27. package/ide/vscode/package.json +1 -1
  28. package/package.json +3 -3
  29. package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +3 -1
  30. package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +3 -1
  31. package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +9 -3
  32. package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +3 -4
  33. package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +3 -1
  34. package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +6 -8
  35. package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +6 -14
  36. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +3 -7
  37. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryDialog.stx +6 -2
  38. package/resources/components/Dashboard/Content/BlogPostEditorDialog.stx +2 -8
  39. package/resources/components/Dashboard/Content/PageEditorDialog.stx +3 -7
  40. package/resources/components/Dashboard/Content/PostEditorDialog.stx +3 -4
  41. package/resources/components/Dashboard/Data/DataModelRecords.stx +12 -75
  42. package/resources/components/Dashboard/Data/DataStatCards.stx +110 -0
  43. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +20 -36
  44. package/resources/components/Dashboard/Marketing/MarketingListDialog.stx +7 -14
  45. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +3 -2
  46. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +10 -13
  47. package/resources/components/Dashboard/Models/ModelFilterPanel.stx +166 -0
  48. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +18 -0
  49. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +3 -2
  50. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +96 -29
  51. package/resources/components/Dashboard/Models/ModelRegion.stx +25 -0
  52. package/resources/components/Dashboard/Models/ModelRegionFor.stx +31 -0
  53. package/resources/components/Dashboard/Operations/RecoveryDestinationDialog.stx +2 -2
  54. package/resources/components/Dashboard/Operations/RecoveryPolicyDialog.stx +3 -1
  55. package/resources/components/Dashboard/Operations/RecoveryRestoreDialog.stx +3 -1
  56. package/resources/components/Dashboard/Settings/AppearanceSettingsDashboard.stx +11 -14
  57. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +6 -9
  58. package/resources/components/Dashboard/UI/Toggle.stx +16 -12
  59. package/resources/functions/dashboard/regions.ts +113 -0
  60. package/resources/functions/dashboard/sidebar.ts +2 -0
  61. package/views/dashboard/composables/useModelList.ts +52 -0
  62. package/views/dashboard/composables/useModelRecord.ts +46 -0
  63. package/views/dashboard/stores/model-page.ts +105 -0
@@ -54,7 +54,7 @@ export default new Action({
54
54
  poster: payload.poster,
55
55
  status: payload.status,
56
56
  author_id: payload.authorId,
57
- is_featured: payload.featured ? 1 : 0,
57
+ is_featured: Boolean(payload.featured),
58
58
  published_at: publishedAtFor(payload.status, existing.published_at, timestamp()),
59
59
  updated_at: timestamp(),
60
60
  } as any)
@@ -65,8 +65,8 @@ describe('marketing list records', () => {
65
65
  slug: 'product-news',
66
66
  description: 'Weekly updates',
67
67
  status: 'active',
68
- isPublic: 1,
69
- doubleOptIn: 0,
68
+ isPublic: true,
69
+ doubleOptIn: false,
70
70
  })
71
71
  })
72
72
 
@@ -145,8 +145,8 @@ export function marketingListWriteData(input: Record<string, unknown>): {
145
145
  slug: string
146
146
  description: string
147
147
  status: MarketingListStatus
148
- isPublic: number
149
- doubleOptIn: number
148
+ isPublic: boolean
149
+ doubleOptIn: boolean
150
150
  } {
151
151
  const name = text(input.name).trim()
152
152
  const slug = slugifyMarketingList(text(input.slug).trim() || name)
@@ -155,8 +155,8 @@ export function marketingListWriteData(input: Record<string, unknown>): {
155
155
  slug,
156
156
  description: text(input.description).trim(),
157
157
  status: status(input.status),
158
- isPublic: boolean(input.isPublic ?? input.is_public) ? 1 : 0,
159
- doubleOptIn: boolean(input.doubleOptIn ?? input.double_opt_in) ? 1 : 0,
158
+ isPublic: boolean(input.isPublic ?? input.is_public),
159
+ doubleOptIn: boolean(input.doubleOptIn ?? input.double_opt_in),
160
160
  }
161
161
  }
162
162
 
@@ -7,9 +7,11 @@ import { safeGet } from '../../../../resources/functions/dashboard/data'
7
7
  import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
8
8
  import { dashboardOperationalError } from '../dashboard-response'
9
9
  import { type ModelCustomAction, modelActionApplies, modelActions, publicModelAction } from './model-actions'
10
+ import { applyModelFilters, type ModelFilter, type ModelFilterValue, modelFilters, modelSortableColumns, parseFilters, withStoredChoices } from './model-filters'
10
11
  import { modelFormFields, reachableRelations } from './model-forms'
11
12
  import { isUnmigratedTable } from './model-migration'
12
13
  import { recordNames } from './model-options'
14
+ import { modelSwitchColumns, modelSwitchFields } from './model-switches'
13
15
  import type { ModelFieldDisplay } from './model-fields'
14
16
  import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelColumnDisplay, modelColumnLabel, modelFieldProblems, modelListColumns, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
15
17
 
@@ -17,6 +19,7 @@ import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreat
17
19
  const warnedColumns = new Set<string>()
18
20
  /** Models already told, this process, what is wrong with their `dashboard.fields`. */
19
21
  const warnedFields = new Set<string>()
22
+ const warnedFilters = new Set<string>()
20
23
 
21
24
  /**
22
25
  * `GET /api/dashboard/models/{slug}` (stacksjs/stacks#1838).
@@ -66,7 +69,11 @@ interface ResponseShape {
66
69
  sort: string
67
70
  dir: 'asc' | 'desc'
68
71
  q: string
69
- filters: Record<string, string>
72
+ filters: Record<string, ModelFilterValue>
73
+ /** What the list can be narrowed by, derived from the model's fields: see `./model-filters`. */
74
+ filterable: ModelFilter[]
75
+ /** The columns the list can be ordered by. */
76
+ sortable: string[]
70
77
  writable: boolean
71
78
  writeCapabilities: ModelWriteCapabilities
72
79
  createFields: ModelCreateField[]
@@ -160,40 +167,8 @@ function queryValue(request: RequestInstance, key: string, fallback = ''): strin
160
167
  return value == null ? fallback : String(value)
161
168
  }
162
169
 
163
- /** `filters` arrives as a JSON object so column names stay unambiguous. */
164
- export function parseFilters(raw: string | null): Record<string, string> {
165
- if (!raw) return {}
166
-
167
- if (raw.length > 8192)
168
- throw new TypeError('Model filters must be 8 KB or smaller')
169
-
170
- let parsed: unknown
171
- try {
172
- parsed = JSON.parse(raw)
173
- }
174
- catch (error) {
175
- throw new Error(`Could not parse model filters: ${error instanceof Error ? error.message : String(error)}`)
176
- }
177
-
178
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
179
- throw new TypeError('Model filters must be a JSON object')
180
-
181
- const entries = Object.entries(parsed)
182
- if (entries.length > 50)
183
- throw new TypeError('Model filters may contain at most 50 columns')
184
-
185
- const out: Record<string, string> = {}
186
- for (const [key, value] of entries) {
187
- if (!/^\w+$/.test(key))
188
- throw new TypeError(`Invalid model filter column "${key}"`)
189
- if (value === null || value === undefined || value === '')
190
- continue
191
- if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean')
192
- throw new TypeError(`Model filter "${key}" must be a scalar value`)
193
- out[key] = String(value)
194
- }
195
- return out
196
- }
170
+ // Where it used to live, and where its callers still look for it.
171
+ export { parseFilters }
197
172
 
198
173
  export default new Action({
199
174
  name: 'Dashboard Model Show',
@@ -213,7 +188,7 @@ export default new Action({
213
188
  const requestedSort = queryValue(request, 'sort').trim()
214
189
  const dir: 'asc' | 'desc' = queryValue(request, 'dir') === 'asc' ? 'asc' : 'desc'
215
190
  const q = queryValue(request, 'q').trim()
216
- let filters: Record<string, string>
191
+ let filters: Record<string, ModelFilterValue>
217
192
  try {
218
193
  filters = parseFilters(queryValue(request, 'filters') || null)
219
194
  }
@@ -240,6 +215,8 @@ export default new Action({
240
215
  dir,
241
216
  q,
242
217
  filters,
218
+ filterable: [],
219
+ sortable: [],
243
220
  writable: false,
244
221
  writeCapabilities: { create: false, update: false, destroy: false, invite: false, anonymize: false },
245
222
  createFields: [],
@@ -293,12 +270,25 @@ export default new Action({
293
270
  response.sort = sort
294
271
  const searchColumns = searchColumnsFor(allowed, first)
295
272
 
273
+ // What the list offers to be narrowed and ordered by, from the model's
274
+ // own fields. Read before the query: a comparison that does not suit a
275
+ // field (a range of days on a name) is refused, not sent to the database.
276
+ const offered = modelFilters(Model, response.columns)
277
+ offered.filters = await withStoredChoices(response.tableName, offered.filters)
278
+ response.filterable = offered.filters
279
+ response.sortable = modelSortableColumns(Model, response.columns)
280
+ if (offered.problems.length > 0 && !warnedFilters.has(modelName)) {
281
+ warnedFilters.add(modelName)
282
+ for (const problem of offered.problems)
283
+ console.warn(`[dashboard] ${modelName} dashboard.filters: ${problem}. It is left out.`)
284
+ }
285
+ const called = (column: string) => modelColumnLabel(Model, column)
286
+ const narrowed = applyModelFilters(Model.query() as any, filters, offered.filters, called)
287
+ if (narrowed.error)
288
+ return routerResponse.json({ message: narrowed.error }, 422)
289
+
296
290
  const build = () => {
297
- let chain = Model.query() as any
298
- for (const [column, value] of Object.entries(filters)) {
299
- if (!isSafeColumn(column, allowed)) continue
300
- chain = chain.where(column, value)
301
- }
291
+ let chain = applyModelFilters(Model.query() as any, filters, offered.filters).query as any
302
292
  if (q && searchColumns.length > 0) {
303
293
  // Lowercased on both sides, so the search ignores case on every
304
294
  // dialect. A model query's whereLike is a plain LIKE, which is
@@ -372,8 +362,10 @@ export default new Action({
372
362
  }
373
363
  const formFields = (): ModelCreateField[] => modelFormFields(Model, reachable)
374
364
  response.createFields = response.writeCapabilities.create ? formFields() : []
375
- response.updateColumns = response.writeCapabilities.update ? modelWritableColumns(Model) : []
376
- response.updateFields = response.writeCapabilities.update ? formFields() : []
365
+ // An edit form also has the switches a trait keeps for itself: a
366
+ // confirmed email, two-factor. Asked for, so no longer shown as read only.
367
+ response.updateColumns = response.writeCapabilities.update ? [...modelWritableColumns(Model), ...modelSwitchColumns(Model)] : []
368
+ response.updateFields = response.writeCapabilities.update ? [...formFields(), ...modelSwitchFields(Model)] : []
377
369
  response.displayColumns = response.columns.filter(col => !col.startsWith('_'))
378
370
  response.columnMeta = response.displayColumns.map((name) => {
379
371
  const format = modelColumnDisplay(Model, name)
@@ -406,6 +398,13 @@ export default new Action({
406
398
  // read "3", and a record's page has its names without asking again.
407
399
  for (const [column, relation] of Object.entries(response.relations)) {
408
400
  const ids = response.rows.map(row => row[column]).filter(id => id !== null && id !== undefined && id !== '') as Array<number | string>
401
+ // And the records the list is narrowed by, which a list with no rows
402
+ // has none of: "Team: PrimeSoft Ltd" in the filter's chip, not "#1".
403
+ const narrowedBy = filters[column]
404
+ if (typeof narrowedBy === 'string')
405
+ ids.push(narrowedBy)
406
+ else if (narrowedBy && 'in' in narrowedBy)
407
+ ids.push(...narrowedBy.in)
409
408
  if (ids.length > 0)
410
409
  response.relationNames[column] = Object.fromEntries(await recordNames(relation.model, ids))
411
410
  }
@@ -4,6 +4,7 @@ import { isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stack
4
4
  import { response } from '@stacksjs/router'
5
5
  import { dashboardOperationalError } from '../dashboard-response'
6
6
  import { missingRelationErrors } from './model-relations'
7
+ import { planSwitches, requestedSwitches, storedSwitches } from './model-switches'
7
8
  import { duplicateFieldErrors, humanizeIdentifier, parseRowId, prepareModelFields, resolveWritableModel } from './model-write'
8
9
 
9
10
  interface ModelWriteInput {
@@ -45,15 +46,28 @@ export default new Action({
45
46
  if (Object.keys(prepared.errors).length > 0)
46
47
  return response.json({ message: 'Validation failed.', errors: prepared.errors }, 422)
47
48
  const changes = toSnakeCaseKeys(prepared.data)
48
- if (Object.keys(changes).length === 0)
49
+ // What a trait keeps for itself (a confirmed email, two-factor) is asked
50
+ // for as a switch and changed by the trait's own function.
51
+ const { asked, errors: unreadable } = requestedSwitches(resolved.Model, body)
52
+ if (Object.keys(unreadable).length > 0)
53
+ return response.json({ message: 'Validation failed.', errors: unreadable }, 422)
54
+ if (Object.keys(changes).length === 0 && asked.length === 0)
49
55
  return response.json({ message: 'No writable fields in the request body.' }, 422)
50
56
 
51
57
  try {
52
58
  const row = await resolved.Model.find(id)
53
59
  if (!row)
54
60
  return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
55
- await resolved.Model.update(id, changes)
56
- return { ok: true, id, changed: Object.keys(changes) }
61
+ // Refused before anything is written: a switch that cannot be turned
62
+ // that way refuses the whole save, like any other field's rule.
63
+ const { turning, errors } = planSwitches(resolved.Model, asked, asked.length > 0 ? await storedSwitches(resolved.Model, id) : {})
64
+ if (Object.keys(errors).length > 0)
65
+ return response.json({ message: 'Validation failed.', errors }, 422)
66
+ if (Object.keys(changes).length > 0)
67
+ await resolved.Model.update(id, changes)
68
+ for (const request of turning)
69
+ await request.switch.set(id, request.on)
70
+ return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
57
71
  }
58
72
  catch (error) {
59
73
  // The model's own rules rejected the row: the caller's mistake, named
@@ -0,0 +1,429 @@
1
+ /**
2
+ * The filters a model's list offers, and how each narrows the query.
3
+ *
4
+ * Nothing declares a filter. A model already says what its fields are, and
5
+ * that is enough to know which of them a list is worth narrowing by and how
6
+ * to ask: a field with a few allowed values is chosen from them, a yes-or-no
7
+ * is yes or no, a field that points at another record is that record, a
8
+ * moment is a range of days. Three things the model already says decide it:
9
+ *
10
+ * - **what the field is**, from its validation rule;
11
+ * - **what the author thinks results are narrowed by**:
12
+ * `traits.useSearch.filterable`, written for the search engine and true
13
+ * of a list as well;
14
+ * - **what must stay private**: a hidden column is never offered, since
15
+ * narrowing by a value is a way to read it.
16
+ *
17
+ * `dashboard.filters` is the override, in the vocabulary `dashboard.columns`
18
+ * uses: the fields to offer, in order.
19
+ *
20
+ * Free text is not a filter. That is what the search box is for, and a box
21
+ * that only finds an exact match (which is what every column had) finds
22
+ * nothing for "act" under Status.
23
+ */
24
+ import { db, sqlDateTime } from '@stacksjs/database/runtime'
25
+ import { belongsToRelations } from './model-relations'
26
+ import { humanizeIdentifier, modelColumnLabel, modelFieldType } from './model-write'
27
+
28
+ /** How a filter is asked for. `text` is an exact value: only for a field the model named. */
29
+ export type ModelFilterKind = 'choice' | 'boolean' | 'relation' | 'date' | 'datetime' | 'number' | 'text'
30
+
31
+ export interface ModelFilter {
32
+ /** The column it narrows. */
33
+ name: string
34
+ label: string
35
+ kind: ModelFilterKind
36
+ /** For `choice`: the values the field may hold, as stored and as read. */
37
+ options?: Array<{ value: string, label: string }>
38
+ /**
39
+ * For `choice`: the options are the values the table holds now, not ones
40
+ * the model's rule limits the field to. A value that is not among them
41
+ * matches nothing; it is not refused, since the list can be a moment old.
42
+ */
43
+ open?: boolean
44
+ /** For `relation`: the model the column points at, to pick a record of. */
45
+ relation?: { slug: string, label: string }
46
+ }
47
+
48
+ /**
49
+ * A filter's value as it arrives. Plain text is "exactly this" (which is
50
+ * what a link from a record's panel sends: `{ team_id: "3" }`). The rest say
51
+ * how: any of several, between two moments, between two numbers.
52
+ */
53
+ export type ModelFilterValue = string | { in: string[] } | { from?: string, to?: string } | { min?: number, max?: number }
54
+
55
+ /** The most values one "any of" may carry. */
56
+ const IN_LIMIT = 50
57
+
58
+ function snakeCase(name: string): string {
59
+ return name.replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase()
60
+ }
61
+
62
+ /** A model's attributes by the column each is stored in. */
63
+ function attributesByColumn(Model: any): Map<string, { name: string, definition: any }> {
64
+ const byColumn = new Map<string, { name: string, definition: any }>()
65
+ for (const [name, definition] of Object.entries((Model?.attributes ?? {}) as Record<string, any>))
66
+ byColumn.set(snakeCase(name), { name, definition })
67
+ return byColumn
68
+ }
69
+
70
+ /** The columns a model's own search trait says results are narrowed by. */
71
+ function searchFilterable(Model: any): string[] {
72
+ const names = Model?.traits?.useSearch?.filterable
73
+ return Array.isArray(names) ? names.filter((name): name is string => typeof name === 'string' && name.trim() !== '').map(name => snakeCase(name.trim())) : []
74
+ }
75
+
76
+ /**
77
+ * The filters a model's list offers, of the columns the page may see.
78
+ *
79
+ * `allowed` is those columns: the list endpoint has already left out the
80
+ * hidden ones, so a filter is never built for a column it does not hold.
81
+ */
82
+ export function modelFilters(Model: any, allowed: readonly string[]): { filters: ModelFilter[], problems: string[] } {
83
+ const attributes = attributesByColumn(Model)
84
+ const relations = belongsToRelations(Model)
85
+ const has = (column: string) => allowed.includes(column)
86
+ const problems: string[] = []
87
+
88
+ /** The filter for one column, or null when its kind is not one a list narrows by. */
89
+ const filterFor = (column: string, named: boolean): ModelFilter | null => {
90
+ if (!has(column))
91
+ return null
92
+ const relation = relations.find(candidate => candidate.column === column)
93
+ const label = modelColumnLabel(Model, column, relation ? humanizeIdentifier(relation.model) : undefined)
94
+ if (relation)
95
+ return { name: column, label, kind: 'relation', relation: { slug: relation.slug, label: humanizeIdentifier(relation.model) } }
96
+ // The columns a trait adds, which the model's attributes do not list.
97
+ if (column === 'created_at' || column === 'updated_at' || column === 'deleted_at')
98
+ return { name: column, label, kind: 'datetime' }
99
+
100
+ const attribute = attributes.get(column)
101
+ if (!attribute)
102
+ return null
103
+ const kind = modelFieldType(attribute.name, attribute.definition)
104
+ if (kind === 'enum') {
105
+ const values: unknown[] = attribute.definition?.validation?.rule?.allowedValues ?? []
106
+ return { name: column, label, kind: 'choice', options: values.map(value => ({ value: String(value), label: humanizeIdentifier(String(value)) })) }
107
+ }
108
+ if (kind === 'boolean')
109
+ return { name: column, label, kind: 'boolean' }
110
+ if (kind === 'date' || kind === 'datetime')
111
+ return { name: column, label, kind }
112
+ // A number or a line of text is only a filter when the model names it:
113
+ // every count and every name would otherwise be one.
114
+ if (kind === 'number')
115
+ return named ? { name: column, label, kind: 'number' } : null
116
+ if (kind === 'text' || kind === 'email' || kind === 'url')
117
+ return named ? { name: column, label, kind: 'text' } : null
118
+ // Prose and structures are searched, not filtered.
119
+ return null
120
+ }
121
+
122
+ /** A declared name, as `dashboard.columns` reads one: an attribute, a column, or a `belongsTo`. */
123
+ const resolve = (name: string): string | null => {
124
+ const column = snakeCase(name.trim())
125
+ const relation = relations.find(candidate => candidate.column === `${column}_id` || snakeCase(candidate.model) === column)
126
+ return has(column) ? column : relation && has(relation.column) ? relation.column : null
127
+ }
128
+
129
+ const declared = Model?.dashboard?.filters
130
+ if (Array.isArray(declared)) {
131
+ const filters: ModelFilter[] = []
132
+ for (const name of declared) {
133
+ if (typeof name !== 'string' || !name.trim()) {
134
+ problems.push('an entry is not a field name')
135
+ continue
136
+ }
137
+ const column = resolve(name)
138
+ const filter = column ? filterFor(column, true) : null
139
+ if (!column)
140
+ problems.push(`'${name}' is not a field the list has`)
141
+ else if (!filter)
142
+ problems.push(`'${name}' is prose or a structure, which a list is searched for and not filtered by`)
143
+ else if (!filters.some(existing => existing.name === filter.name))
144
+ filters.push(filter)
145
+ }
146
+ return { filters, problems }
147
+ }
148
+
149
+ // Derived. The ones the model's search trait names come first, then the
150
+ // rest in the order that reads best in a menu: what a record is, what it
151
+ // points at, when it happened.
152
+ const filters: ModelFilter[] = []
153
+ const add = (filter: ModelFilter | null) => {
154
+ if (filter && !filters.some(existing => existing.name === filter.name))
155
+ filters.push(filter)
156
+ }
157
+ for (const name of searchFilterable(Model)) {
158
+ const column = resolve(name)
159
+ if (column)
160
+ add(filterFor(column, true))
161
+ }
162
+ const derived = allowed.map(column => filterFor(column, false)).filter((filter): filter is ModelFilter => filter !== null)
163
+ for (const kind of ['choice', 'boolean', 'relation', 'date', 'datetime'] as const) {
164
+ for (const filter of derived.filter(candidate => candidate.kind === kind))
165
+ add(filter)
166
+ }
167
+ return { filters, problems }
168
+ }
169
+
170
+ /**
171
+ * The columns a list may be ordered by, of the ones the page may see.
172
+ *
173
+ * Any stored value that has an order a person would recognise. Not prose or
174
+ * a structure, and not a column that points at another record: the cell
175
+ * shows that record's name, and ordering by its id would look random.
176
+ */
177
+ export function modelSortableColumns(Model: any, allowed: readonly string[]): string[] {
178
+ const attributes = attributesByColumn(Model)
179
+ const relations = new Set(belongsToRelations(Model).map(relation => relation.column))
180
+ return allowed.filter((column) => {
181
+ if (relations.has(column))
182
+ return false
183
+ const attribute = attributes.get(column)
184
+ if (!attribute)
185
+ return true
186
+ const kind = modelFieldType(attribute.name, attribute.definition)
187
+ return kind !== 'json' && kind !== 'longtext' && kind !== 'markdown'
188
+ })
189
+ }
190
+
191
+ /** The most distinct values a field of text may hold and still be chosen from. */
192
+ const CHOICE_LIMIT = 20
193
+ /** How long a table's distinct values are remembered. */
194
+ const CHOICES_TTL = 30_000
195
+ const storedChoices = new Map<string, { at: number, values: string[] | null }>()
196
+
197
+ /** The distinct values a column holds, up to `limit`. */
198
+ async function distinctValues(table: string, column: string, limit: number): Promise<unknown[]> {
199
+ const rows = await db.selectFrom(table as never).select([column] as never).groupBy(column as never).limit(limit).execute() as Array<Record<string, unknown>>
200
+ return rows.map(row => row[column])
201
+ }
202
+
203
+ /**
204
+ * Turn a field of text the model named into a choice, when the table holds
205
+ * few enough values to choose from.
206
+ *
207
+ * A model can name `status` as something results are narrowed by without
208
+ * limiting what it holds (`schema.string()`). Asked for as text, it would be
209
+ * a box that finds only an exact match. What the table holds says what there
210
+ * is to choose: "active" and "inactive". A field with many values (a
211
+ * `source` of a thousand referrers) stays a box.
212
+ *
213
+ * Remembered for half a minute per column: the list is read on every page,
214
+ * sort and keystroke, and a distinct read of a column with no index reads
215
+ * the whole table.
216
+ */
217
+ export async function withStoredChoices(
218
+ table: string,
219
+ filters: ModelFilter[],
220
+ read: (table: string, column: string, limit: number) => Promise<unknown[]> = distinctValues,
221
+ now: number = Date.now(),
222
+ ): Promise<ModelFilter[]> {
223
+ const out: ModelFilter[] = []
224
+ for (const filter of filters) {
225
+ if (filter.kind !== 'text') {
226
+ out.push(filter)
227
+ continue
228
+ }
229
+ const key = `${table}.${filter.name}`
230
+ let known = storedChoices.get(key)
231
+ if (!known || now - known.at > CHOICES_TTL) {
232
+ let values: string[] | null = null
233
+ try {
234
+ const found = (await read(table, filter.name, CHOICE_LIMIT + 1))
235
+ .filter(value => value !== null && value !== undefined && String(value) !== '')
236
+ .map(String)
237
+ values = found.length > 0 && found.length <= CHOICE_LIMIT ? [...new Set(found)].sort((a, b) => a.localeCompare(b)) : null
238
+ }
239
+ catch {
240
+ // The field is still a filter; it is just asked for as text.
241
+ values = null
242
+ }
243
+ known = { at: now, values }
244
+ storedChoices.set(key, known)
245
+ }
246
+ out.push(known.values
247
+ ? { ...filter, kind: 'choice', open: true, options: known.values.map(value => ({ value, label: humanizeIdentifier(value) })) }
248
+ : filter)
249
+ }
250
+ return out
251
+ }
252
+
253
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
254
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
255
+ }
256
+
257
+ /** `filters` arrives as a JSON object so column names stay unambiguous. */
258
+ export function parseFilters(raw: string | null): Record<string, ModelFilterValue> {
259
+ if (!raw) return {}
260
+
261
+ if (raw.length > 8192)
262
+ throw new TypeError('Model filters must be 8 KB or smaller')
263
+
264
+ let parsed: unknown
265
+ try {
266
+ parsed = JSON.parse(raw)
267
+ }
268
+ catch (error) {
269
+ throw new Error(`Could not parse model filters: ${error instanceof Error ? error.message : String(error)}`)
270
+ }
271
+
272
+ if (!isPlainObject(parsed))
273
+ throw new TypeError('Model filters must be a JSON object')
274
+
275
+ const entries = Object.entries(parsed)
276
+ if (entries.length > 50)
277
+ throw new TypeError('Model filters may contain at most 50 columns')
278
+
279
+ const out: Record<string, ModelFilterValue> = {}
280
+ for (const [key, value] of entries) {
281
+ if (!/^\w+$/.test(key))
282
+ throw new TypeError(`Invalid model filter column "${key}"`)
283
+ if (value === null || value === undefined || value === '')
284
+ continue
285
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
286
+ out[key] = String(value)
287
+ continue
288
+ }
289
+ if (!isPlainObject(value))
290
+ throw new TypeError(`Model filter "${key}" must be a value, or an object saying how to compare`)
291
+
292
+ const keys = Object.keys(value)
293
+ if (keys.length === 1 && keys[0] === 'in') {
294
+ const list = value.in
295
+ if (!Array.isArray(list) || list.some(item => typeof item !== 'string' && typeof item !== 'number'))
296
+ throw new TypeError(`Model filter "${key}" must list the values to match`)
297
+ if (list.length > IN_LIMIT)
298
+ throw new TypeError(`Model filter "${key}" may list at most ${IN_LIMIT} values`)
299
+ const values = [...new Set(list.map(String).filter(item => item !== ''))]
300
+ if (values.length > 0)
301
+ out[key] = { in: values }
302
+ continue
303
+ }
304
+ if (keys.length > 0 && keys.every(name => name === 'from' || name === 'to')) {
305
+ const range: { from?: string, to?: string } = {}
306
+ for (const edge of ['from', 'to'] as const) {
307
+ const moment = value[edge]
308
+ if (moment === undefined || moment === null || moment === '')
309
+ continue
310
+ if (typeof moment !== 'string' || moment.length > 40)
311
+ throw new TypeError(`Model filter "${key}" ${edge} must be a date`)
312
+ range[edge] = moment
313
+ }
314
+ if (range.from !== undefined || range.to !== undefined)
315
+ out[key] = range
316
+ continue
317
+ }
318
+ if (keys.length > 0 && keys.every(name => name === 'min' || name === 'max')) {
319
+ const range: { min?: number, max?: number } = {}
320
+ for (const edge of ['min', 'max'] as const) {
321
+ const amount = value[edge]
322
+ if (amount === undefined || amount === null || amount === '')
323
+ continue
324
+ const number = typeof amount === 'number' ? amount : typeof amount === 'string' && amount.trim() !== '' ? Number(amount) : Number.NaN
325
+ if (!Number.isFinite(number))
326
+ throw new TypeError(`Model filter "${key}" ${edge} must be a number`)
327
+ range[edge] = number
328
+ }
329
+ if (range.min !== undefined || range.max !== undefined)
330
+ out[key] = range
331
+ continue
332
+ }
333
+ throw new TypeError(`Model filter "${key}" is not a comparison the list has: use a value, { in }, { from, to } or { min, max }`)
334
+ }
335
+ return out
336
+ }
337
+
338
+ /** A day as a date column stores it. */
339
+ const DAY = /^\d{4}-\d{2}-\d{2}$/
340
+
341
+ /** A model's query, as far as a filter needs it. */
342
+ interface FilterQuery {
343
+ where: (...args: any[]) => FilterQuery
344
+ whereIn: (column: string, values: unknown[]) => FilterQuery
345
+ }
346
+
347
+ /**
348
+ * Narrow a query by the filters that arrived, or say why one cannot be
349
+ * applied. Every column has already been checked against the ones the page
350
+ * may see; what is checked here is that the comparison suits the field.
351
+ */
352
+ export function applyModelFilters<Query extends FilterQuery>(
353
+ query: Query,
354
+ values: Record<string, ModelFilterValue>,
355
+ filters: readonly ModelFilter[],
356
+ label: (column: string) => string = column => column,
357
+ ): { query: Query, error: string | null } {
358
+ let chain: FilterQuery = query
359
+ for (const [column, value] of Object.entries(values)) {
360
+ const filter = filters.find(candidate => candidate.name === column)
361
+ const called = filter?.label ?? label(column)
362
+ // Any column the page may see can be matched exactly, as a link from a
363
+ // record's panel does. Comparing another way is for the list's filters.
364
+ if (!filter && typeof value !== 'string')
365
+ return { query, error: `${called} is not one of this list's filters, so it can only be matched exactly.` }
366
+
367
+ if (typeof value === 'string') {
368
+ if (filter?.kind === 'boolean') {
369
+ const yes = ['true', '1', 'yes'].includes(value.toLowerCase())
370
+ if (!yes && !['false', '0', 'no'].includes(value.toLowerCase()))
371
+ return { query, error: `${called} is yes or no.` }
372
+ chain = chain.where(column, yes)
373
+ }
374
+ else if (filter?.kind === 'choice' && !filter.open && !filter.options!.some(option => option.value === value)) {
375
+ return { query, error: `${called} cannot be "${value}".` }
376
+ }
377
+ else {
378
+ chain = chain.where(column, value)
379
+ }
380
+ continue
381
+ }
382
+
383
+ if ('in' in value) {
384
+ if (filter!.kind !== 'choice' && filter!.kind !== 'relation' && filter!.kind !== 'text')
385
+ return { query, error: `${called} cannot be matched against a list of values.` }
386
+ if (filter!.kind === 'choice' && !filter!.open) {
387
+ const unknown = value.in.find(item => !filter!.options!.some(option => option.value === item))
388
+ if (unknown !== undefined)
389
+ return { query, error: `${called} cannot be "${unknown}".` }
390
+ }
391
+ chain = chain.whereIn(column, value.in)
392
+ continue
393
+ }
394
+
395
+ if ('from' in value || 'to' in value) {
396
+ if (filter!.kind !== 'date' && filter!.kind !== 'datetime')
397
+ return { query, error: `${called} is not a date, so it has no range of days.` }
398
+ for (const edge of ['from', 'to'] as const) {
399
+ const given = value[edge]
400
+ if (given === undefined)
401
+ continue
402
+ if (filter!.kind === 'date') {
403
+ // A day, compared as the column stores days: both ends included.
404
+ if (!DAY.test(given) || Number.isNaN(Date.parse(given)))
405
+ return { query, error: `${called} ${edge} must be a day, as 2026-01-31.` }
406
+ chain = chain.where(column, edge === 'from' ? '>=' : '<=', given)
407
+ }
408
+ else {
409
+ // A moment. The page sends where the viewer's day starts and where
410
+ // the day after their last one does, so "to" is not included.
411
+ const moment = new Date(given)
412
+ if (Number.isNaN(moment.getTime()))
413
+ return { query, error: `${called} ${edge} must be a date and time.` }
414
+ chain = chain.where(column, edge === 'from' ? '>=' : '<', sqlDateTime(moment))
415
+ }
416
+ }
417
+ continue
418
+ }
419
+
420
+ if (filter!.kind !== 'number')
421
+ return { query, error: `${called} is not a number, so it has no minimum or maximum.` }
422
+ const range = value as { min?: number, max?: number }
423
+ if (range.min !== undefined)
424
+ chain = chain.where(column, '>=', range.min)
425
+ if (range.max !== undefined)
426
+ chain = chain.where(column, '<=', range.max)
427
+ }
428
+ return { query: chain as Query, error: null }
429
+ }