@stacksjs/defaults 0.70.355 → 0.70.356

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 (155) hide show
  1. package/ai/skills/stacks-email/SKILL.md +38 -1
  2. package/app/Actions/ContactAction.ts +2 -2
  3. package/app/Actions/Dashboard/Analytics/EventAnalyticsAction.ts +2 -3
  4. package/app/Actions/Dashboard/Analytics/MarketingAnalyticsAction.ts +2 -3
  5. package/app/Actions/Dashboard/Analytics/SalesAnalyticsAction.ts +2 -3
  6. package/app/Actions/Dashboard/Analytics/WebAnalyticsAction.ts +9 -3
  7. package/app/Actions/Dashboard/Auth/MeAction.ts +4 -7
  8. package/app/Actions/Dashboard/Buddy/BuddyChatAction.ts +2 -3
  9. package/app/Actions/Dashboard/Cloud/CloudIndexAction.ts +8 -1
  10. package/app/Actions/Dashboard/Cloud/ServerlessIndexAction.ts +15 -8
  11. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +2 -4
  12. package/app/Actions/Dashboard/Commerce/CommerceCouponsAction.ts +2 -4
  13. package/app/Actions/Dashboard/Commerce/CommerceCustomersAction.ts +2 -4
  14. package/app/Actions/Dashboard/Commerce/CommerceDashboardAction.ts +2 -4
  15. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +2 -4
  16. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +2 -4
  17. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +2 -4
  18. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +2 -4
  19. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +2 -4
  20. package/app/Actions/Dashboard/Commerce/CommercePosCheckoutAction.ts +75 -61
  21. package/app/Actions/Dashboard/Commerce/CommercePrintDevicesAction.ts +2 -4
  22. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +2 -4
  23. package/app/Actions/Dashboard/Commerce/CommerceProductDetailAction.ts +3 -4
  24. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +2 -4
  25. package/app/Actions/Dashboard/Commerce/CommerceTaxesAction.ts +2 -4
  26. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +2 -4
  27. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +2 -4
  28. package/app/Actions/Dashboard/Commerce/DriverIndexAction.ts +2 -4
  29. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +2 -4
  30. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +2 -4
  31. package/app/Actions/Dashboard/Commerce/ManufacturerIndexAction.ts +2 -4
  32. package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +2 -4
  33. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +2 -4
  34. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +2 -4
  35. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +2 -4
  36. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +2 -4
  37. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +2 -4
  38. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +2 -4
  39. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +2 -4
  40. package/app/Actions/Dashboard/DashboardActivityAction.ts +2 -5
  41. package/app/Actions/Dashboard/Data/ActivityIndexAction.ts +2 -5
  42. package/app/Actions/Dashboard/Data/SubscriberIndexAction.ts +2 -5
  43. package/app/Actions/Dashboard/Data/TeamIndexAction.ts +2 -5
  44. package/app/Actions/Dashboard/Data/UserIndexAction.ts +2 -5
  45. package/app/Actions/Dashboard/Deployments/CreateDeployment.ts +23 -19
  46. package/app/Actions/Dashboard/Deployments/GetAverageDeploymentTime.ts +8 -2
  47. package/app/Actions/Dashboard/Deployments/GetDeployScript.ts +3 -6
  48. package/app/Actions/Dashboard/Deployments/GetDeployment.ts +4 -5
  49. package/app/Actions/Dashboard/Deployments/GetDeploymentCount.ts +7 -1
  50. package/app/Actions/Dashboard/Deployments/GetDeploymentLiveTerminalOutput.ts +10 -9
  51. package/app/Actions/Dashboard/Deployments/GetDeployments.ts +2 -4
  52. package/app/Actions/Dashboard/Deployments/GetRecentDeployments.ts +8 -2
  53. package/app/Actions/Dashboard/Deployments/UpdateDeployScript.ts +18 -5
  54. package/app/Actions/Dashboard/Email/CapturedMailIndexAction.ts +2 -4
  55. package/app/Actions/Dashboard/Email/CapturedMailShowAction.ts +3 -4
  56. package/app/Actions/Dashboard/Infrastructure/InsightsAction.ts +15 -14
  57. package/app/Actions/Dashboard/Infrastructure/LogIndexAction.ts +2 -8
  58. package/app/Actions/Dashboard/Jobs/JobIndexAction.ts +2 -4
  59. package/app/Actions/Dashboard/Jobs/JobShowAction.ts +13 -8
  60. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +2 -4
  61. package/app/Actions/Dashboard/Kanban/BoardDestroyAction.ts +2 -3
  62. package/app/Actions/Dashboard/Kanban/BoardShowAction.ts +2 -3
  63. package/app/Actions/Dashboard/Kanban/BoardStoreAction.ts +2 -3
  64. package/app/Actions/Dashboard/Kanban/BoardUpdateAction.ts +2 -3
  65. package/app/Actions/Dashboard/Kanban/BoardsIndexAction.ts +2 -3
  66. package/app/Actions/Dashboard/Kanban/BoardsReorderAction.ts +2 -3
  67. package/app/Actions/Dashboard/Kanban/CardAssigneesSyncAction.ts +2 -3
  68. package/app/Actions/Dashboard/Kanban/CardCommentDestroyAction.ts +2 -3
  69. package/app/Actions/Dashboard/Kanban/CardCommentStoreAction.ts +2 -3
  70. package/app/Actions/Dashboard/Kanban/CardCommentUpdateAction.ts +2 -3
  71. package/app/Actions/Dashboard/Kanban/CardDestroyAction.ts +2 -3
  72. package/app/Actions/Dashboard/Kanban/CardLabelsSyncAction.ts +2 -3
  73. package/app/Actions/Dashboard/Kanban/CardShowAction.ts +2 -3
  74. package/app/Actions/Dashboard/Kanban/CardStoreAction.ts +2 -3
  75. package/app/Actions/Dashboard/Kanban/CardUpdateAction.ts +2 -3
  76. package/app/Actions/Dashboard/Kanban/CardsReorderAction.ts +2 -3
  77. package/app/Actions/Dashboard/Kanban/ColumnDestroyAction.ts +2 -3
  78. package/app/Actions/Dashboard/Kanban/ColumnStoreAction.ts +2 -3
  79. package/app/Actions/Dashboard/Kanban/ColumnUpdateAction.ts +2 -3
  80. package/app/Actions/Dashboard/Kanban/ColumnsReorderAction.ts +2 -3
  81. package/app/Actions/Dashboard/Kanban/LabelDestroyAction.ts +2 -3
  82. package/app/Actions/Dashboard/Kanban/LabelStoreAction.ts +2 -3
  83. package/app/Actions/Dashboard/Kanban/LabelUpdateAction.ts +2 -3
  84. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +2 -3
  85. package/app/Actions/Dashboard/Kanban/kanban-response.ts +5 -0
  86. package/app/Actions/Dashboard/Library/CreateComponent.ts +15 -6
  87. package/app/Actions/Dashboard/Library/CreateFunction.ts +15 -6
  88. package/app/Actions/Dashboard/Library/DependencyIndexAction.ts +88 -77
  89. package/app/Actions/Dashboard/Library/GetAverageReleaseTime.ts +21 -15
  90. package/app/Actions/Dashboard/Library/GetComponents.ts +14 -7
  91. package/app/Actions/Dashboard/Library/GetDownloadCount.ts +14 -5
  92. package/app/Actions/Dashboard/Library/GetFunctions.ts +12 -5
  93. package/app/Actions/Dashboard/Library/GetReleaseCount.ts +14 -5
  94. package/app/Actions/Dashboard/Library/GetReleases.ts +17 -10
  95. package/app/Actions/Dashboard/Library/PackageIndexAction.ts +14 -7
  96. package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +7 -5
  97. package/app/Actions/Dashboard/Models/ModelShowAction.ts +82 -174
  98. package/app/Actions/Dashboard/Models/ModelStoreAction.ts +6 -4
  99. package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +9 -7
  100. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +47 -17
  101. package/app/Actions/Dashboard/Models/model-write.ts +20 -5
  102. package/app/Actions/Dashboard/Notifications/NotificationDeliveryHistoryAction.ts +46 -36
  103. package/app/Actions/Dashboard/Notifications/NotificationDeliveryIndexAction.ts +14 -6
  104. package/app/Actions/Dashboard/Notifications/NotificationDeliveryOverviewAction.ts +96 -84
  105. package/app/Actions/Dashboard/Notifications/NotificationDeliveryRetryAction.ts +34 -21
  106. package/app/Actions/Dashboard/Queries/QueryDashboardAction.ts +2 -4
  107. package/app/Actions/Dashboard/Queries/QueryShowAction.ts +2 -3
  108. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +2 -4
  109. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +2 -4
  110. package/app/Actions/Dashboard/Rbac/PermissionDestroyAction.ts +2 -2
  111. package/app/Actions/Dashboard/Rbac/PermissionStoreAction.ts +2 -2
  112. package/app/Actions/Dashboard/Rbac/PermissionsIndexAction.ts +2 -3
  113. package/app/Actions/Dashboard/Rbac/RoleDestroyAction.ts +2 -2
  114. package/app/Actions/Dashboard/Rbac/RolePermissionsShowAction.ts +2 -2
  115. package/app/Actions/Dashboard/Rbac/RolePermissionsSyncAction.ts +2 -6
  116. package/app/Actions/Dashboard/Rbac/RoleStoreAction.ts +2 -2
  117. package/app/Actions/Dashboard/Rbac/RolesIndexAction.ts +4 -6
  118. package/app/Actions/Dashboard/Rbac/UserRolesShowAction.ts +2 -2
  119. package/app/Actions/Dashboard/Rbac/UserRolesSyncAction.ts +2 -9
  120. package/app/Actions/Dashboard/Rbac/UsersListAction.ts +2 -3
  121. package/app/Actions/Dashboard/Rbac/rbac-response.ts +10 -0
  122. package/app/Actions/Dashboard/Realtime/RealtimeStatsAction.ts +2 -4
  123. package/app/Actions/Dashboard/Search/GlobalSearchAction.ts +68 -55
  124. package/app/Actions/Dashboard/Teams/TeamInvitationDestroyAction.ts +34 -16
  125. package/app/Actions/Dashboard/Teams/TeamInvitationResendAction.ts +52 -29
  126. package/app/Actions/Dashboard/Teams/TeamInviteAction.ts +102 -71
  127. package/app/Actions/Dashboard/Teams/TeamMemberDestroyAction.ts +36 -17
  128. package/app/Actions/Dashboard/Teams/TeamMemberUpdateAction.ts +39 -26
  129. package/app/Actions/Dashboard/Teams/TeamPeopleIndexAction.ts +71 -58
  130. package/app/Actions/Dashboard/Teams/team-invitation-delivery.ts +29 -7
  131. package/app/Actions/Dashboard/Teams/team-member-count.ts +4 -2
  132. package/app/Actions/Dashboard/Teams/team-records.test.ts +2 -0
  133. package/app/Actions/Dashboard/Teams/team-records.ts +2 -0
  134. package/app/Actions/Dashboard/dashboard-response.ts +16 -0
  135. package/app/Actions/SendWelcomeEmail.ts +1 -1
  136. package/app/Actions/Teams/AcceptInvitationAction.ts +74 -51
  137. package/app/Actions/Teams/ShowInvitationAction.ts +21 -14
  138. package/app/Actions/Teams/team-response.ts +23 -0
  139. package/app/Mail/OrderConfirmation.ts +1 -1
  140. package/app/Mail/SubscriptionConfirmation.ts +1 -1
  141. package/app/Mail/TeamInvitation.ts +1 -1
  142. package/app/Models/EmailIdempotency.ts +64 -0
  143. package/app/Models/EmailSuppression.ts +52 -0
  144. package/app/Models/EmailWebhookEvent.ts +51 -0
  145. package/app/Models/TeamInvitation.ts +13 -0
  146. package/functions/data.ts +0 -1
  147. package/functions/jobs.ts +0 -1
  148. package/ide/vscode/package.json +1 -1
  149. package/package.json +1 -1
  150. package/resources/components/Dashboard/Data/DataRecords.stx +0 -4
  151. package/resources/components/Dashboard/Jobs/JobDetail.stx +3 -2
  152. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +7 -13
  153. package/resources/components/Dashboard/Models/ModelsOverview.stx +1 -1
  154. package/views/dashboard/.discovered-models.json +30 -0
  155. package/views/dashboard/stores/auth.ts +15 -14
@@ -1,8 +1,8 @@
1
1
  import type { RequestInstance } from '@stacksjs/types'
2
2
  import { Action } from '@stacksjs/actions'
3
- import { env } from '@stacksjs/env'
4
3
  import { response as routerResponse } from '@stacksjs/router'
5
4
  import { loadModelIfExists, safeGet } from '../../../../resources/functions/dashboard/data'
5
+ import { dashboardOperationalError } from '../dashboard-response'
6
6
  import { isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelCreateFields, modelSchemaColumns, modelWriteCapabilities, slugToPascal } from './model-write'
7
7
 
8
8
  /**
@@ -23,8 +23,8 @@ import { isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, m
23
23
  * queries, so scopes, casts and accessors all apply.
24
24
  * 2. `loadModelIfExists(Name)` — path-map lookup, covers models the ORM has not
25
25
  * registered as a global.
26
- * 3. Raw SQLite last resort for a table with no model file at all
27
- * (lookup/pivot tables, or a schema added outside the ORM).
26
+ * A missing model is a 404. The generic browser never bypasses model scopes,
27
+ * casts, observers, connection drivers, or the app override contract.
28
28
  */
29
29
 
30
30
  interface ColumnMeta {
@@ -50,8 +50,6 @@ interface ResponseShape {
50
50
  dir: 'asc' | 'desc'
51
51
  q: string
52
52
  filters: Record<string, string>
53
- source: 'orm' | 'sqlite-fallback'
54
- /** False for tables reached through the SQLite fallback: no model, no writes. */
55
53
  writable: boolean
56
54
  writeCapabilities: ModelWriteCapabilities
57
55
  createFields: ModelCreateField[]
@@ -85,6 +83,15 @@ function humanize(column: string): string {
85
83
  // filter by it.
86
84
  const HIDDEN_COLUMNS = new Set(['password', 'remember_token', 'api_token', 'access_token', 'refresh_token', 'secret', 'two_factor_secret'])
87
85
 
86
+ function hiddenModelColumns(Model: any): Set<string> {
87
+ const hidden = new Set(HIDDEN_COLUMNS)
88
+ for (const [name, definition] of Object.entries(Model?.attributes ?? {})) {
89
+ if ((definition as { hidden?: boolean })?.hidden)
90
+ hidden.add(pascalToSnake(name))
91
+ }
92
+ return hidden
93
+ }
94
+
88
95
  /**
89
96
  * Column identifiers reach the query builder as raw, unquoted SQL, so only
90
97
  * valid identifiers from the table's own column list may ever be used.
@@ -151,15 +158,6 @@ export function parseFilters(raw: string | null): Record<string, string> {
151
158
  return out
152
159
  }
153
160
 
154
- /**
155
- * Signals that a free-text search spans several columns, which the query
156
- * builder cannot express (`whereLike` is single-column and `orWhere` only
157
- * takes equality pairs). The SQLite path builds that OR with bound
158
- * parameters instead. Distinct from a real failure so it never surfaces
159
- * to the page as an error.
160
- */
161
- class SearchUnsupported extends Error {}
162
-
163
161
  function resolveOrmModel(modelName: string): any {
164
162
  const injected = (globalThis as Record<string, any>)[modelName]
165
163
  // The ORM injects Proxies that answer `undefined` for every property
@@ -213,182 +211,92 @@ export default new Action({
213
211
  dir,
214
212
  q,
215
213
  filters,
216
- source: 'orm',
217
214
  writable: false,
218
215
  writeCapabilities: { create: false, update: false, destroy: false },
219
216
  createFields: [],
220
217
  error: null,
221
218
  }
222
219
 
223
- const Model = resolveOrmModel(modelName) ?? await loadModelIfExists(modelName)
224
- const hasOrm = Boolean(Model) && typeof Model.where === 'function'
225
-
226
- if (hasOrm) {
227
- try {
228
- response.tableName = String(Model.table || tableName)
229
- // The column list has to come from a real row: the ORM does not
230
- // expose a database schema reflection API. Empty tables fall back
231
- // to the model definition, which is also the migration source.
232
- const probe = await Model.orderByDesc('id').take(1).get() as Array<Record<string, unknown>>
233
- const first = Array.isArray(probe) ? probe[0] : undefined
234
- const shape = first && typeof first === 'object'
235
- ? ((first as { attributes?: Record<string, unknown> }).attributes ?? first)
236
- : {}
237
- response.columns = Object.keys(shape).filter(k => typeof k === 'string' && !k.startsWith('_'))
238
- if (response.columns.length === 0)
239
- response.columns = modelSchemaColumns(Model)
240
-
241
- const allowed = new Set(response.columns.filter(c => !HIDDEN_COLUMNS.has(c)))
242
- const unknownFilter = Object.keys(filters).find(column => !isSafeColumn(column, allowed))
243
- if (unknownFilter)
244
- return routerResponse.json({ message: `Unknown model filter column "${unknownFilter}".` }, 422)
245
- if (requestedSort && !isSafeColumn(requestedSort, allowed))
246
- return routerResponse.json({ message: `Unknown model sort column "${requestedSort}".` }, 422)
247
-
248
- const sort = isSafeColumn(requestedSort, allowed)
249
- ? requestedSort
250
- : (allowed.has('id') ? 'id' : (response.columns[0] ?? ''))
251
- response.sort = sort
252
-
253
- // Text columns are decided from the probe row, before any query is
254
- // built, so the search clause does not depend on response metadata
255
- // that is only assembled after the rows come back.
256
- const searchColumns = [...allowed].filter(c => typeof safeGet(first, c, null) === 'string')
257
-
258
- const build = () => {
259
- let chain = Model as any
260
- for (const [column, value] of Object.entries(filters)) {
261
- if (!isSafeColumn(column, allowed)) continue
262
- chain = chain.where(column, value)
263
- }
264
- // Global search is a LIKE across every text column. The builder's
265
- // `whereLike` covers one column and `orWhere` only takes equality
266
- // pairs, so a multi-column OR-LIKE has no ORM expression; that
267
- // case is served by the SQLite path below instead, which builds
268
- // the OR with bound parameters. Writes stay enabled either way,
269
- // because the model still exists.
270
- if (q && searchColumns.length === 1)
271
- chain = chain.whereLike(searchColumns[0], `%${q}%`)
272
- return chain
273
- }
274
-
275
- // A multi-column search has no ORM expression, so hand that one
276
- // query to the SQLite path — without recording an error, because it
277
- // is a gap in the builder's vocabulary, not a failure.
278
- if (q && searchColumns.length > 1)
279
- throw new SearchUnsupported()
280
-
281
- response.totalCount = q && searchColumns.length === 0
282
- ? 0
283
- : await build().count()
284
- const rows = response.totalCount === 0
285
- ? []
286
- : await build()
287
- .orderBy(sort, dir)
288
- .skip((page - 1) * perPage)
289
- .take(perPage)
290
- .get() as Array<Record<string, unknown>>
291
-
292
- // Flatten to plain JSON-safe objects — proxy models and
293
- // accessor-rich rows do not serialise cleanly across the wire.
294
- response.rows = (Array.isArray(rows) ? rows : []).map((row) => {
295
- const flat: Record<string, unknown> = {}
296
- for (const col of response.columns)
297
- flat[col] = safeGet(row, col, null)
298
- return flat
299
- })
300
- }
301
- catch (e) {
302
- if (e instanceof SearchUnsupported) {
303
- response.source = 'sqlite-fallback'
304
- }
305
- else {
306
- return routerResponse.json({
307
- message: `Could not query model ${modelName}: ${e instanceof Error ? e.message : String(e)}`,
308
- }, 503)
309
- }
310
- }
220
+ let Model: any
221
+ try {
222
+ Model = resolveOrmModel(modelName) ?? await loadModelIfExists(modelName)
311
223
  }
312
- else {
313
- response.source = 'sqlite-fallback'
224
+ catch (error) {
225
+ return dashboardOperationalError(error, `${modelName} could not be loaded.`, 'ModelShowAction.resolve')
314
226
  }
227
+ if (!Model || typeof Model.where !== 'function')
228
+ return routerResponse.json({ message: `No ORM model named ${modelName}.` }, 404)
315
229
 
316
- if (response.source === 'sqlite-fallback') {
317
- try {
318
- const { Database } = await import('bun:sqlite')
319
- const db = new Database(env.DB_DATABASE_PATH || 'database/stacks.sqlite', { readonly: true })
320
- try {
321
- if (!/^[A-Za-z_]\w*$/.test(response.tableName))
322
- return routerResponse.json({ message: `Model table "${response.tableName}" is not a safe SQL identifier.` }, 500)
323
-
324
- const tableInfo = db.query(`PRAGMA table_info(${response.tableName})`).all() as Array<{ name: string, type: string }>
325
- if (tableInfo.length === 0)
326
- return routerResponse.json({ message: `Model table "${response.tableName}" does not exist.` }, 404)
327
-
328
- response.columns = tableInfo.map(c => c.name)
329
-
330
- if (response.columns.length > 0) {
331
- const allowed = new Set(response.columns.filter(c => !HIDDEN_COLUMNS.has(c)))
332
- const unknownFilter = Object.keys(filters).find(column => !isSafeColumn(column, allowed))
333
- if (unknownFilter)
334
- return routerResponse.json({ message: `Unknown model filter column "${unknownFilter}".` }, 422)
335
- if (requestedSort && !isSafeColumn(requestedSort, allowed))
336
- return routerResponse.json({ message: `Unknown model sort column "${requestedSort}".` }, 422)
337
-
338
- const sort = isSafeColumn(requestedSort, allowed)
339
- ? requestedSort
340
- : (allowed.has('id') ? 'id' : response.columns[0])
341
- response.sort = sort
342
-
343
- // Every value is bound; only identifiers are interpolated, and
344
- // those come from the allowlist built out of PRAGMA above.
345
- const wheres: string[] = []
346
- const values: unknown[] = []
347
- for (const [column, value] of Object.entries(filters)) {
348
- if (!isSafeColumn(column, allowed)) continue
349
- wheres.push(`${column} = ?`)
350
- values.push(value)
351
- }
352
- if (q) {
353
- const textColumns = tableInfo
354
- .filter(c => allowed.has(c.name) && /char|text|clob/i.test(c.type || ''))
355
- .map(c => c.name)
356
- if (textColumns.length > 0) {
357
- wheres.push(`(${textColumns.map(c => `${c} LIKE ?`).join(' OR ')})`)
358
- for (const _ of textColumns) values.push(`%${q}%`)
359
- }
360
- }
361
- const whereSql = wheres.length > 0 ? ` WHERE ${wheres.join(' AND ')}` : ''
362
-
363
- const countRow = db.query(`SELECT COUNT(*) as count FROM ${response.tableName}${whereSql}`).get(...values as any[]) as { count?: number } | null
364
- response.totalCount = countRow?.count ?? 0
365
- response.rows = db
366
- .query(`SELECT * FROM ${response.tableName}${whereSql} ORDER BY ${sort} ${dir.toUpperCase()} LIMIT ? OFFSET ?`)
367
- .all(...values as any[], perPage, (page - 1) * perPage) as Array<Record<string, unknown>>
368
- response.error = null
369
- }
230
+ try {
231
+ response.tableName = String(Model.table || tableName)
232
+ const probe = await Model.orderByDesc('id').take(1).get() as Array<Record<string, unknown>>
233
+ const first = Array.isArray(probe) ? probe[0] : undefined
234
+ const shape = first && typeof first === 'object'
235
+ ? ((first as { attributes?: Record<string, unknown> }).attributes ?? first)
236
+ : {}
237
+ const hiddenColumns = hiddenModelColumns(Model)
238
+ response.columns = Object.keys(shape).filter(k => typeof k === 'string' && !k.startsWith('_') && !hiddenColumns.has(k))
239
+ if (response.columns.length === 0)
240
+ response.columns = modelSchemaColumns(Model).filter(column => !hiddenColumns.has(column))
241
+
242
+ const allowed = new Set(response.columns)
243
+ const unknownFilter = Object.keys(filters).find(column => !isSafeColumn(column, allowed))
244
+ if (unknownFilter)
245
+ return routerResponse.json({ message: `Unknown model filter column "${unknownFilter}".` }, 422)
246
+ if (requestedSort && !isSafeColumn(requestedSort, allowed))
247
+ return routerResponse.json({ message: `Unknown model sort column "${requestedSort}".` }, 422)
248
+
249
+ const sort = isSafeColumn(requestedSort, allowed)
250
+ ? requestedSort
251
+ : (allowed.has('id') ? 'id' : (response.columns[0] ?? ''))
252
+ response.sort = sort
253
+ const searchColumns = [...allowed].filter(c => typeof safeGet(first, c, null) === 'string')
254
+
255
+ const build = () => {
256
+ let chain = Model.query() as any
257
+ for (const [column, value] of Object.entries(filters)) {
258
+ if (!isSafeColumn(column, allowed)) continue
259
+ chain = chain.where(column, value)
370
260
  }
371
- finally {
372
- db.close()
261
+ if (q && searchColumns.length > 0) {
262
+ chain = chain.whereGroup((group: any) => {
263
+ for (const [index, column] of searchColumns.entries()) {
264
+ group = index === 0
265
+ ? group.whereLike(column, `%${q}%`)
266
+ : group.orWhereLike(column, `%${q}%`)
267
+ }
268
+ return group
269
+ })
373
270
  }
271
+ return chain
374
272
  }
375
- catch (e) {
376
- return routerResponse.json({
377
- message: `Could not query table ${response.tableName}: ${e instanceof Error ? e.message : String(e)}`,
378
- }, 503)
379
- }
273
+
274
+ response.totalCount = q && searchColumns.length === 0
275
+ ? 0
276
+ : await build().count()
277
+ const rows = response.totalCount === 0
278
+ ? []
279
+ : await build()
280
+ .orderBy(sort, dir)
281
+ .skip((page - 1) * perPage)
282
+ .take(perPage)
283
+ .get() as Array<Record<string, unknown>>
284
+
285
+ response.rows = (Array.isArray(rows) ? rows : []).map((row) => {
286
+ const flat: Record<string, unknown> = {}
287
+ for (const col of response.columns)
288
+ flat[col] = safeGet(row, col, null)
289
+ return flat
290
+ })
291
+ }
292
+ catch (error) {
293
+ return dashboardOperationalError(error, `${modelName} records could not be loaded.`, 'ModelShowAction.query')
380
294
  }
381
295
 
382
- // Writability follows the model's declared useApi routes, not which
383
- // engine answered this particular query. A multi-column search can be
384
- // served by SQLite for a model that still creates and updates through
385
- // the ORM.
386
- response.writeCapabilities = hasOrm
387
- ? modelWriteCapabilities(Model)
388
- : { create: false, update: false, destroy: false }
296
+ response.writeCapabilities = modelWriteCapabilities(Model)
389
297
  response.writable = Object.values(response.writeCapabilities).some(Boolean)
390
298
  response.createFields = response.writeCapabilities.create ? modelCreateFields(Model) : []
391
- response.displayColumns = response.columns.filter(col => !HIDDEN_COLUMNS.has(col) && !col.startsWith('_'))
299
+ response.displayColumns = response.columns.filter(col => !col.startsWith('_'))
392
300
  response.columnMeta = response.displayColumns.map(name => ({
393
301
  name,
394
302
  label: humanize(name),
@@ -1,6 +1,8 @@
1
1
  import type { RequestInstance } from '@stacksjs/types'
2
2
  import { Action } from '@stacksjs/actions'
3
3
  import { toSnakeCaseKeys } from '@stacksjs/orm'
4
+ import { response } from '@stacksjs/router'
5
+ import { dashboardOperationalError } from '../dashboard-response'
4
6
  import { prepareModelFields, resolveWritableModel } from './model-write'
5
7
 
6
8
  interface ModelWriteInput {
@@ -15,7 +17,7 @@ export default new Action({
15
17
  async handle(request: RequestInstance<ModelWriteInput>) {
16
18
  const resolved = await resolveWritableModel(request.getParam('slug'), 'store')
17
19
  if ('error' in resolved)
18
- return { ok: false, error: resolved.error }
20
+ return response.json({ message: resolved.error }, resolved.status)
19
21
 
20
22
  const input = request.all()
21
23
  const raw = input.fields
@@ -23,9 +25,9 @@ export default new Action({
23
25
  const { data, errors } = prepareModelFields(resolved.Model, body)
24
26
 
25
27
  if (Object.keys(errors).length > 0)
26
- return { ok: false, error: 'Validation failed.', errors }
28
+ return response.json({ message: 'Validation failed.', errors }, 422)
27
29
  if (Object.keys(data).length === 0)
28
- return { ok: false, error: 'No fillable fields in the request body.' }
30
+ return response.json({ message: 'No fillable fields in the request body.' }, 422)
29
31
 
30
32
  try {
31
33
  const row = await resolved.Model.create(toSnakeCaseKeys(data))
@@ -33,7 +35,7 @@ export default new Action({
33
35
  return { ok: true, id }
34
36
  }
35
37
  catch (error) {
36
- return { ok: false, error: error instanceof Error ? error.message : String(error) }
38
+ return dashboardOperationalError(error, 'The model record could not be created.', 'ModelStoreAction', 500)
37
39
  }
38
40
  },
39
41
  })
@@ -1,6 +1,8 @@
1
1
  import type { RequestInstance } from '@stacksjs/types'
2
2
  import { Action } from '@stacksjs/actions'
3
3
  import { toSnakeCaseKeys } from '@stacksjs/orm'
4
+ import { response } from '@stacksjs/router'
5
+ import { dashboardOperationalError } from '../dashboard-response'
4
6
  import { parseRowId, prepareModelFields, resolveWritableModel } from './model-write'
5
7
 
6
8
  interface ModelWriteInput {
@@ -23,11 +25,11 @@ export default new Action({
23
25
  async handle(request: RequestInstance<ModelWriteInput>) {
24
26
  const resolved = await resolveWritableModel(request.getParam('slug'), 'update')
25
27
  if ('error' in resolved)
26
- return { ok: false, error: resolved.error }
28
+ return response.json({ message: resolved.error }, resolved.status)
27
29
 
28
30
  const id = parseRowId(request.getParam('id'))
29
31
  if (id === null)
30
- return { ok: false, error: 'A numeric row id is required.' }
32
+ return response.json({ message: 'A numeric row id is required.' }, 400)
31
33
 
32
34
  // Edits arrive nested under `fields`. The router's input bag merges the
33
35
  // body with route params and query, so a flat payload would silently
@@ -40,20 +42,20 @@ export default new Action({
40
42
  const body = (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw as Record<string, unknown> : {}
41
43
  const prepared = prepareModelFields(resolved.Model, body, true)
42
44
  if (Object.keys(prepared.errors).length > 0)
43
- return { ok: false, error: 'Validation failed.', errors: prepared.errors }
45
+ return response.json({ message: 'Validation failed.', errors: prepared.errors }, 422)
44
46
  const changes = toSnakeCaseKeys(prepared.data)
45
47
  if (Object.keys(changes).length === 0)
46
- return { ok: false, error: 'No writable fields in the request body.' }
48
+ return response.json({ message: 'No writable fields in the request body.' }, 422)
47
49
 
48
50
  try {
49
51
  const row = await resolved.Model.find(id)
50
52
  if (!row)
51
- return { ok: false, error: `${resolved.modelName} ${id} not found.` }
53
+ return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
52
54
  await resolved.Model.update(id, changes)
53
55
  return { ok: true, id, changed: Object.keys(changes) }
54
56
  }
55
- catch (e) {
56
- return { ok: false, error: e instanceof Error ? e.message : String(e) }
57
+ catch (error) {
58
+ return dashboardOperationalError(error, 'The model record could not be updated.', 'ModelUpdateAction', 500)
57
59
  }
58
60
  },
59
61
  })
@@ -3,6 +3,7 @@ import { existsSync, readdirSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import process from 'node:process'
5
5
  import { countRows } from '../../../../resources/functions/dashboard/data'
6
+ import { dashboardOperationalError, dashboardOperationalIssue } from '../dashboard-response'
6
7
  import { modelApiConfiguration } from './model-api'
7
8
 
8
9
  /**
@@ -41,6 +42,12 @@ interface ModelGroup {
41
42
  countLabel: string
42
43
  }
43
44
 
45
+ interface DiscoveredModel {
46
+ name: string
47
+ file: string
48
+ source: 'userland' | 'framework'
49
+ }
50
+
44
51
  function pascalToSnake(s: string): string {
45
52
  return s.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()
46
53
  }
@@ -92,6 +99,21 @@ function categoryLabel(k: string): string {
92
99
  return k === 'userland' ? 'Your Models' : k.charAt(0).toUpperCase() + k.slice(1)
93
100
  }
94
101
 
102
+ function unavailableModelRow(model: DiscoveredModel, error: string): ModelRow {
103
+ return {
104
+ name: model.name,
105
+ table: pluralize(pascalToSnake(model.name)),
106
+ href: `/models/${pascalToKebab(model.name)}`,
107
+ count: null,
108
+ attributeCount: 0,
109
+ category: categorize(model),
110
+ source: model.source,
111
+ apiUri: '',
112
+ apiRoutes: [],
113
+ error,
114
+ }
115
+ }
116
+
95
117
  export default new Action({
96
118
  name: 'Dashboard Models Index',
97
119
  description: 'List every model + live record count for the dashboard models overview.',
@@ -102,11 +124,18 @@ export default new Action({
102
124
  const userlandDir = join(cwd, 'app', 'Models')
103
125
  const defaultsDir = join(cwd, 'storage/framework/defaults/app/Models')
104
126
 
105
- const userland = walkModels(userlandDir, false)
106
- const defaults = walkModels(defaultsDir, true)
127
+ let userland: Array<Omit<DiscoveredModel, 'source'>>
128
+ let defaults: Array<Omit<DiscoveredModel, 'source'>>
129
+ try {
130
+ userland = walkModels(userlandDir, false)
131
+ defaults = walkModels(defaultsDir, true)
132
+ }
133
+ catch (error) {
134
+ return dashboardOperationalError(error, 'Model catalog could not be loaded.', 'ModelsIndexAction.catalog')
135
+ }
107
136
 
108
137
  const seen = new Set<string>()
109
- const merged: Array<{ name: string, file: string, source: 'userland' | 'framework' }> = []
138
+ const merged: DiscoveredModel[] = []
110
139
  for (const list of [userland, defaults]) {
111
140
  for (const m of list) {
112
141
  if (seen.has(m.name)) continue
@@ -122,28 +151,29 @@ export default new Action({
122
151
  Model = module.default ?? module
123
152
  }
124
153
  catch (error) {
125
- return {
126
- name: m.name,
127
- table: pluralize(pascalToSnake(m.name)),
128
- href: `/models/${pascalToKebab(m.name)}`,
129
- count: null,
130
- attributeCount: 0,
131
- category: categorize(m),
132
- source: m.source,
133
- apiUri: '',
134
- apiRoutes: [],
135
- error: error instanceof Error ? error.message : String(error),
136
- }
154
+ return unavailableModelRow(
155
+ m,
156
+ dashboardOperationalIssue(error, 'Model definition could not be loaded.', `ModelsIndexAction.import.${m.name}`),
157
+ )
137
158
  }
138
159
 
139
- const api = modelApiConfiguration(Model)
160
+ let api: ReturnType<typeof modelApiConfiguration>
161
+ try {
162
+ api = modelApiConfiguration(Model)
163
+ }
164
+ catch (error) {
165
+ return unavailableModelRow(
166
+ m,
167
+ dashboardOperationalIssue(error, 'Model metadata could not be loaded.', `ModelsIndexAction.metadata.${m.name}`),
168
+ )
169
+ }
140
170
  let count: number | null = null
141
171
  let error: string | null = null
142
172
  try {
143
173
  count = await countRows(Model)
144
174
  }
145
175
  catch (cause) {
146
- error = cause instanceof Error ? cause.message : String(cause)
176
+ error = dashboardOperationalIssue(cause, 'Model count could not be loaded.', `ModelsIndexAction.count.${m.name}`)
147
177
  }
148
178
 
149
179
  return {
@@ -7,6 +7,7 @@
7
7
  * bypass every guarantee the ORM makes. Those rows stay read-only.
8
8
  */
9
9
  import { loadModelIfExists } from '../../../../resources/functions/dashboard/data'
10
+ import { dashboardOperationalIssue } from '../dashboard-response'
10
11
  import { modelApiConfiguration } from './model-api'
11
12
 
12
13
  /** Never writable from a generic admin table, whatever the model declares. */
@@ -42,6 +43,11 @@ export interface ResolvedModel {
42
43
  modelName: string
43
44
  }
44
45
 
46
+ export interface ModelResolutionError {
47
+ error: string
48
+ status: 400 | 404 | 405 | 500
49
+ }
50
+
45
51
  export type ModelWriteOperation = 'store' | 'update' | 'destroy'
46
52
 
47
53
  export interface ModelWriteCapabilities {
@@ -285,19 +291,28 @@ export function prepareModelFields(
285
291
  * injects (the same object the rest of the dashboard queries, so scopes,
286
292
  * casts and observers all apply) over the path-map lookup.
287
293
  */
288
- export async function resolveWritableModel(slug: string, operation?: ModelWriteOperation): Promise<ResolvedModel | { error: string }> {
294
+ export async function resolveWritableModel(slug: string, operation?: ModelWriteOperation): Promise<ResolvedModel | ModelResolutionError> {
289
295
  if (!isValidModelSlug(slug))
290
- return { error: 'Model slug must be lowercase kebab-case.' }
296
+ return { error: 'Model slug must be lowercase kebab-case.', status: 400 }
291
297
 
292
298
  const modelName = slugToPascal(slug)
293
299
  const injected = (globalThis as Record<string, any>)[modelName]
294
- const Model = (injected && typeof injected.where === 'function') ? injected : await loadModelIfExists(modelName)
300
+ let Model: any
301
+ try {
302
+ Model = (injected && typeof injected.where === 'function') ? injected : await loadModelIfExists(modelName)
303
+ }
304
+ catch (error) {
305
+ return {
306
+ error: dashboardOperationalIssue(error, `${modelName} could not be loaded.`, `resolveWritableModel.${operation || 'read'}`),
307
+ status: 500,
308
+ }
309
+ }
295
310
  if (!Model || typeof Model.find !== 'function')
296
- return { error: `No ORM model named ${modelName}. Rows from tables without a model are read-only.` }
311
+ return { error: `No ORM model named ${modelName}. Rows from tables without a model are read-only.`, status: 404 }
297
312
  if (operation) {
298
313
  const capability = operation === 'store' ? 'create' : operation
299
314
  if (!modelWriteCapabilities(Model)[capability])
300
- return { error: `${modelName} does not declare the ${operation} route in its useApi trait.` }
315
+ return { error: `${modelName} does not declare the ${operation} route in its useApi trait.`, status: 405 }
301
316
  }
302
317
  return { Model, modelName }
303
318
  }