@stacksjs/defaults 0.75.551 → 0.75.555

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 (58) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +347 -14
  3. package/ai/skills/stacks-desktop/SKILL.md +19 -0
  4. package/ai/skills/stacks-models/SKILL.md +19 -0
  5. package/ai/skills/stacks-native/CATALOG.md +7 -7
  6. package/ai/skills/stacks-storage/SKILL.md +9 -0
  7. package/app/Actions/Dashboard/Content/file-manager.ts +9 -3
  8. package/app/Actions/Dashboard/Data/SubscriberIndexAction.ts +6 -3
  9. package/app/Actions/Dashboard/Data/TeamIndexAction.ts +6 -3
  10. package/app/Actions/Dashboard/Data/UserIndexAction.ts +6 -3
  11. package/app/Actions/Dashboard/Data/data-records.ts +12 -0
  12. package/app/Actions/Dashboard/Models/ModelActionRunAction.ts +77 -0
  13. package/app/Actions/Dashboard/Models/ModelMarkdownAction.ts +42 -0
  14. package/app/Actions/Dashboard/Models/ModelShowAction.ts +63 -21
  15. package/app/Actions/Dashboard/Models/ModelUploadAction.ts +83 -0
  16. package/app/Actions/Dashboard/Models/model-actions.ts +393 -0
  17. package/app/Actions/Dashboard/Models/model-fields.ts +198 -0
  18. package/app/Actions/Dashboard/Models/model-forms.ts +36 -0
  19. package/app/Actions/Dashboard/Models/model-related.ts +62 -11
  20. package/app/Actions/Dashboard/Models/model-upload.ts +81 -0
  21. package/app/Actions/Dashboard/Models/model-write.ts +92 -5
  22. package/app/Actions/Dashboard/Users/UserPasswordResetAction.ts +50 -0
  23. package/app/Actions/Desktop/UpdateArtifactAction.ts +37 -0
  24. package/app/Models/CardAttachment.ts +5 -0
  25. package/app/Models/Deployment.ts +5 -0
  26. package/app/Models/QueryLog.ts +5 -0
  27. package/app/Models/Request.ts +4 -0
  28. package/app/Models/Team.ts +4 -0
  29. package/app/Models/User.ts +18 -0
  30. package/functions/dashboard-markdown.ts +132 -0
  31. package/functions/dashboard-model-bulk.ts +224 -0
  32. package/functions/dashboard-model-format.ts +201 -0
  33. package/functions/dashboard-model-record.test.ts +53 -30
  34. package/functions/dashboard-model-record.ts +267 -19
  35. package/functions/data.ts +9 -0
  36. package/ide/vscode/package.json +1 -1
  37. package/package.json +3 -3
  38. package/resources/components/Dashboard/Data/ActivityLog.stx +212 -0
  39. package/resources/components/Dashboard/Data/DataModelRecords.stx +89 -0
  40. package/resources/components/Dashboard/Models/ModelActionForm.stx +85 -0
  41. package/resources/components/Dashboard/Models/ModelBadge.stx +22 -0
  42. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +43 -9
  43. package/resources/components/Dashboard/Models/ModelMarkdownInput.stx +139 -0
  44. package/resources/components/Dashboard/Models/ModelRecordActions.stx +32 -1
  45. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +1 -1
  46. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +114 -7
  47. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +1 -1
  48. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +387 -20
  49. package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +197 -27
  50. package/resources/components/Dashboard/Models/ModelRelationPicker.stx +3 -0
  51. package/resources/components/Dashboard/Models/ModelUploadInput.stx +97 -0
  52. package/routes/dashboard-api.ts +9 -0
  53. package/routes/desktop-updates.ts +7 -0
  54. package/views/dashboard/data/activity/index.stx +1 -1
  55. package/views/dashboard/data/subscribers.stx +1 -3
  56. package/views/dashboard/data/teams.stx +1 -3
  57. package/views/dashboard/data/users.stx +1 -3
  58. package/resources/components/Dashboard/Data/DataRecords.stx +0 -427
@@ -1,18 +1,24 @@
1
1
  import { describe, expect, it } from 'bun:test'
2
+ import { modelColumnLabel } from '../app/Actions/Dashboard/Models/model-write'
2
3
  import { DashboardApiError } from './dashboard-api'
3
4
  import { modelDeleteNotice, modelDeleteWarning, modelFieldColumn, modelFieldError, modelFieldInputValue, modelFieldPayloadValue, modelFormPayload, modelFormPrefill, modelFormValues, modelListColumnNames, modelListFilters, modelRecordBackHref, modelRecordCreateHref, modelRecordEditHref, modelRecordHref, modelRecordListLabel, modelRecordSections, modelRecordTitle, modelRelatedCreateHref, modelRelatedListHref, modelRelationCell, modelWriteFailure, userInviteHref } from './dashboard-model-record'
4
- import type { ModelCreateField, ModelRecord, ModelRelatedPanel } from './dashboard-model-record'
5
+ import type { ModelColumn, ModelCreateField, ModelRecord, ModelRelatedPanel } from './dashboard-model-record'
6
+
7
+ // ModelShowAction resolves these labels before sending columns to the browser.
8
+ function columnMetadata(columns: Array<Pick<ModelColumn, 'name' | 'type'>>, Model: object = {}, relations: ModelRecord['relations'] = {}): ModelColumn[] {
9
+ return columns.map(column => ({ ...column, label: modelColumnLabel(Model, column.name, relations[column.name]?.label) }))
10
+ }
5
11
 
6
12
  const record: ModelRecord = {
7
13
  modelName: 'Team',
8
14
  row: { id: 4, name: 'PrimeSoft Ltd', description: null, status: 'active', created_at: '2026-08-08' },
9
- columns: [
10
- { name: 'id', label: 'Id', type: 'number' },
11
- { name: 'name', label: 'Name', type: 'text' },
12
- { name: 'description', label: 'Description', type: 'text' },
13
- { name: 'status', label: 'Status', type: 'text' },
14
- { name: 'created_at', label: 'Created At', type: 'date' },
15
- ],
15
+ columns: columnMetadata([
16
+ { name: 'id', type: 'number' },
17
+ { name: 'name', type: 'text' },
18
+ { name: 'description', type: 'text' },
19
+ { name: 'status', type: 'text' },
20
+ { name: 'created_at', type: 'date' },
21
+ ]),
16
22
  updateColumns: ['name', 'description', 'status'],
17
23
  fields: [],
18
24
  relations: {},
@@ -102,21 +108,21 @@ describe('a model record on its own page', () => {
102
108
  modelName: 'User',
103
109
  tableName: 'users',
104
110
  row: { id: 13, uuid: null, name: 'Ava', email: 'ava@example.com', avatar: null, status: 'active', two_factor_enabled: 0, login_count: 4, team_id: 2, meta: { plan: 'pro' }, created_at: '2026-11-05T23:01:51.038Z', updated_at: null, email_verified_at: null },
105
- columns: [
106
- { name: 'id', label: 'ID', type: 'number' },
107
- { name: 'uuid', label: 'Uuid', type: 'text' },
108
- { name: 'name', label: 'Name', type: 'text' },
109
- { name: 'email', label: 'Email', type: 'text' },
110
- { name: 'avatar', label: 'Avatar', type: 'text' },
111
- { name: 'status', label: 'Status', type: 'text' },
112
- { name: 'two_factor_enabled', label: 'Two Factor Enabled', type: 'boolean' },
113
- { name: 'login_count', label: 'Login Count', type: 'number' },
114
- { name: 'team_id', label: 'Team ID', type: 'number' },
115
- { name: 'meta', label: 'Meta', type: 'json' },
116
- { name: 'created_at', label: 'Created At', type: 'date' },
117
- { name: 'updated_at', label: 'Updated At', type: 'date' },
118
- { name: 'email_verified_at', label: 'Email Verified At', type: 'text' },
119
- ],
111
+ columns: columnMetadata([
112
+ { name: 'id', type: 'number' },
113
+ { name: 'uuid', type: 'text' },
114
+ { name: 'name', type: 'text' },
115
+ { name: 'email', type: 'text' },
116
+ { name: 'avatar', type: 'text' },
117
+ { name: 'status', type: 'text' },
118
+ { name: 'two_factor_enabled', type: 'boolean' },
119
+ { name: 'login_count', type: 'number' },
120
+ { name: 'team_id', type: 'number' },
121
+ { name: 'meta', type: 'json' },
122
+ { name: 'created_at', type: 'date' },
123
+ { name: 'updated_at', type: 'date' },
124
+ { name: 'email_verified_at', type: 'text' },
125
+ ]),
120
126
  updateColumns: [],
121
127
  fields: [],
122
128
  relations: {},
@@ -161,6 +167,14 @@ describe('a model record on its own page', () => {
161
167
  expect(sections.map(section => section.id)).toEqual(['information'])
162
168
  })
163
169
 
170
+ it('preserves the model\'s own identifier and timestamp headings', () => {
171
+ const Model = { dashboard: { fields: { uuid: { label: 'Uuid' }, updated_at: { label: 'Updated At' } } } }
172
+ const columns = columnMetadata([{ name: 'uuid', type: 'text' }, { name: 'updated_at', type: 'date' }], Model)
173
+ const by = Object.fromEntries(modelRecordSections({ ...user, columns }).flatMap(section => section.details).map(detail => [detail.name, detail]))
174
+ expect(by.uuid).toMatchObject({ label: 'Uuid', value: 'No uuid', empty: true })
175
+ expect(by.updated_at).toMatchObject({ label: 'Updated At', value: 'Not yet', empty: true })
176
+ })
177
+
164
178
  it('names the list in the breadcrumb', () => {
165
179
  expect(modelRecordListLabel(user, '/data/users')).toBe('Users')
166
180
  expect(modelRecordListLabel({ ...user, tableName: 'product_categories' }, '/models/product-category')).toBe('Product Categories')
@@ -267,18 +281,19 @@ describe('a field that points at another model\'s record', () => {
267
281
  })
268
282
 
269
283
  describe('a record\'s page names the records it points at', () => {
284
+ const relations: ModelRecord['relations'] = { team_id: { model: 'Team', slug: 'team', label: 'Team' }, user_id: { model: 'User', slug: 'user', label: 'User' } }
270
285
  const member: ModelRecord = {
271
286
  modelName: 'Team Member',
272
287
  row: { id: 9, team_id: 3, user_id: null, role: 'member' },
273
- columns: [
274
- { name: 'id', label: 'ID', type: 'number' },
275
- { name: 'team_id', label: 'Team ID', type: 'number' },
276
- { name: 'user_id', label: 'User ID', type: 'number' },
277
- { name: 'role', label: 'Role', type: 'text' },
278
- ],
288
+ columns: columnMetadata([
289
+ { name: 'id', type: 'number' },
290
+ { name: 'team_id', type: 'number' },
291
+ { name: 'user_id', type: 'number' },
292
+ { name: 'role', type: 'text' },
293
+ ], {}, relations),
279
294
  updateColumns: [],
280
295
  fields: [],
281
- relations: { team_id: { model: 'Team', slug: 'team', label: 'Team' }, user_id: { model: 'User', slug: 'user', label: 'User' } },
296
+ relations,
282
297
  relationNames: {},
283
298
  writeCapabilities: { create: true, update: true, destroy: true, invite: false, anonymize: false },
284
299
  anonymized: false,
@@ -302,6 +317,14 @@ describe('a record\'s page names the records it points at', () => {
302
317
  it('leaves the record\'s own id alone', () => {
303
318
  expect(identifiers().find(detail => detail.name === 'id')).toMatchObject({ label: 'ID', value: '9', kind: 'text' })
304
319
  })
320
+
321
+ it('preserves a model\'s relation heading instead of substituting the related model\'s name', () => {
322
+ const Model = { dashboard: { fields: { team: { label: 'Team ID' }, user: { label: 'Owner' } } }, belongsTo: ['Team', 'User'] }
323
+ const columns = columnMetadata([{ name: 'team_id', type: 'number' }, { name: 'user_id', type: 'number' }], Model, relations)
324
+ const by = Object.fromEntries(modelRecordSections({ ...member, columns }, { team_id: 'PrimeSoft Ltd' }).flatMap(section => section.details).map(detail => [detail.name, detail]))
325
+ expect(by.team_id).toMatchObject({ label: 'Team ID', value: 'PrimeSoft Ltd', kind: 'link', href: '/models/team/3' })
326
+ expect(by.user_id).toMatchObject({ label: 'Owner', value: 'No owner', empty: true })
327
+ })
305
328
  })
306
329
 
307
330
  describe('a panel of the records that point at a record', () => {
@@ -13,6 +13,9 @@
13
13
  */
14
14
  import { DashboardApiError, dashboardApi } from './dashboard-api'
15
15
  import { parseDashboardDate } from './dashboard-dates'
16
+ import type { ModelFieldDisplay } from './dashboard-model-format'
17
+ import type { ModelBadgeTone } from './dashboard-model-format'
18
+ import { MODEL_BADGE_COLUMNS, modelBadgeTone, modelColumnIsDate, modelFormattedValue } from './dashboard-model-format'
16
19
 
17
20
  export interface ModelWriteCapabilities {
18
21
  create: boolean
@@ -24,10 +27,38 @@ export interface ModelWriteCapabilities {
24
27
  anonymize: boolean
25
28
  }
26
29
 
30
+ /**
31
+ * Something the model lets an operator do to a record beyond editing it, as
32
+ * a button: "Mark as shipped". From the model's `dashboard.actions`.
33
+ */
34
+ export interface ModelCustomAction {
35
+ /** Its place in the URL that runs it. */
36
+ name: string
37
+ /** What the button says. */
38
+ label: string
39
+ /** An iconify class, or empty for the default. */
40
+ icon: string
41
+ /** What the confirmation says before it runs. Empty runs it at once. */
42
+ confirm: string
43
+ /** It removes or revokes something: drawn in red. */
44
+ destructive: boolean
45
+ /** Where it is offered: the record's page, its row in a list, the rows selected in a list. */
46
+ places: Array<'record' | 'row' | 'bulk'>
47
+ /**
48
+ * What the action has to be told before it runs, from its own
49
+ * `validations`. With any, pressing its button opens a form and not a
50
+ * confirmation.
51
+ */
52
+ fields?: ModelCreateField[]
53
+ }
54
+
27
55
  export interface ModelColumn {
28
56
  name: string
57
+ /** What the field is called: the model's own word for it, else its name in words. */
29
58
  label: string
30
59
  type?: 'number' | 'boolean' | 'date' | 'json' | 'text'
60
+ /** How the model says the value reads (`dashboard.fields`): money, a size, a link. */
61
+ format?: ModelFieldDisplay
31
62
  }
32
63
 
33
64
  export interface ModelRecord {
@@ -47,6 +78,8 @@ export interface ModelRecord {
47
78
  writeCapabilities: ModelWriteCapabilities
48
79
  /** Erased under the app's data-subject rules: its personal details are placeholders. */
49
80
  anonymized: boolean
81
+ /** The model's own actions this record is offered on its page. */
82
+ actions: ModelCustomAction[]
50
83
  }
51
84
 
52
85
  interface ModelShowResponse {
@@ -63,12 +96,14 @@ interface ModelShowResponse {
63
96
  relationNames?: Record<string, Record<string, string>>
64
97
  writeCapabilities?: ModelWriteCapabilities
65
98
  anonymizedIds?: Array<number | string>
99
+ actions?: ModelCustomAction[]
100
+ rowActions?: Record<string, string[]>
66
101
  error?: string | null
67
102
  }
68
103
 
69
104
  /** A field of the create form, from the model's fillable attributes. */
70
105
  /** How a field is asked for: see `modelFieldType` on the server. */
71
- export type ModelFieldType = 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'json' | 'longtext' | 'number' | 'relation' | 'text'
106
+ export type ModelFieldType = 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'json' | 'longtext' | 'markdown' | 'number' | 'relation' | 'text' | 'upload' | 'url'
72
107
 
73
108
  /** The model a field or column points at: `team_id` is a Team. */
74
109
  export interface ModelRelationTarget {
@@ -97,6 +132,10 @@ export interface ModelCreateField {
97
132
  options: string[]
98
133
  /** For a `relation`: the model whose records the picker lists. */
99
134
  relation?: ModelRelationTarget
135
+ /** A sentence under the input, from the model's `dashboard.fields`. */
136
+ help?: string
137
+ /** For an `upload`: the kinds of file that may be chosen, as a file input's `accept` spells them. */
138
+ accept?: string
100
139
  }
101
140
 
102
141
  /** What a form holds for each field: a checkbox's state, or an input's text. */
@@ -163,6 +202,7 @@ export async function fetchModelRecord(slug: string, id: string | number): Promi
163
202
  .filter((entry): entry is readonly [string, string] => typeof entry[1] === 'string')),
164
203
  writeCapabilities: { ...NO_WRITES, ...data.writeCapabilities },
165
204
  anonymized: (data.anonymizedIds ?? []).some(candidate => String(candidate) === String(id)),
205
+ actions: modelActionsFor(data.actions, data.rowActions, id, 'record'),
166
206
  }
167
207
  }
168
208
 
@@ -180,11 +220,14 @@ export interface ModelRecordDetail {
180
220
  /**
181
221
  * How the value is drawn: plain text, an outlined badge for a status-like
182
222
  * word, a check or cross for a boolean, a preformatted block for JSON, a
183
- * link to the record another model's id points at.
223
+ * link to the record another model's id points at, and where the model
224
+ * says so a link out to a web address, a picture or a code font.
184
225
  */
185
- kind: 'text' | 'badge' | 'boolean' | 'json' | 'link'
186
- /** For a link: the page of the record this one points at. */
226
+ kind: 'text' | 'badge' | 'boolean' | 'json' | 'link' | 'external' | 'image' | 'code'
227
+ /** For a link: the page of the record this one points at, or the address it opens. For an image: what it draws. */
187
228
  href?: string
229
+ /** For a badge: what its word says, for its colour. */
230
+ tone?: ModelBadgeTone
188
231
  /** A boolean's answer, for the icon. */
189
232
  yes: boolean
190
233
  /** Takes the card's full width: long text and JSON. */
@@ -200,23 +243,14 @@ export interface ModelRecordSection {
200
243
  }
201
244
 
202
245
  /** Columns whose value is one word out of a few: drawn as a badge. */
203
- const BADGE_COLUMNS = new Set(['status', 'state', 'type', 'role', 'source', 'plan', 'category', 'kind', 'channel', 'driver', 'priority', 'visibility', 'guard_name', 'provider', 'locale', 'currency'])
246
+ const BADGE_COLUMNS = MODEL_BADGE_COLUMNS
204
247
 
205
248
  function isIdentifier(name: string): boolean {
206
249
  return name === 'id' || name === 'uuid' || name.endsWith('_id') || name.endsWith('_uuid')
207
250
  }
208
251
 
209
252
  function isDate(column: ModelColumn): boolean {
210
- return column.type === 'date' || /_(?:at|on)$/.test(column.name)
211
- }
212
-
213
- /** "Created At" reads as "Created", and the update time as "Last Updated". */
214
- function detailLabel(column: ModelColumn): string {
215
- if (column.name === 'updated_at')
216
- return 'Last Updated'
217
- if (column.name === 'uuid')
218
- return 'UUID'
219
- return isDate(column) ? column.label.replace(/\s+(?:At|On)$/i, '') : column.label
253
+ return modelColumnIsDate(column)
220
254
  }
221
255
 
222
256
  /** "No email", "No stripe ID": lower case, except a word that is an acronym. */
@@ -236,8 +270,9 @@ export type ModelRelationNames = Record<string, string>
236
270
  function detail(record: ModelRecord, column: ModelColumn, names: ModelRelationNames = {}): ModelRecordDetail {
237
271
  const stored = record.row[column.name]
238
272
  const relation = record.relations?.[column.name]
239
- // "Team", not "Team ID": the page says which team, and the id is its link.
240
- const label = relation ? relation.label : detailLabel(column)
273
+ // What the list calls it: the model's own word, "Team" and not "Team ID"
274
+ // for a record it points at, "Created" and not "Created At".
275
+ const label = column.label
241
276
  const base = { name: column.name, label, yes: false, wide: false }
242
277
  if (relation && stored !== null && stored !== undefined && stored !== '') {
243
278
  return {
@@ -249,6 +284,14 @@ function detail(record: ModelRecord, column: ModelColumn, names: ModelRelationNa
249
284
  href: modelRecordHref(relation.slug, stored as number | string),
250
285
  }
251
286
  }
287
+ // The model's own say on how the value reads comes before any guess.
288
+ if (column.format) {
289
+ const shown = modelFormattedValue(stored, column.format, record.row)
290
+ if (!shown)
291
+ return { ...base, value: emptyText(column, label), empty: true, kind: 'text' }
292
+ const kind = shown.kind === 'link' ? 'external' : shown.kind
293
+ return { ...base, value: shown.text, empty: false, kind, href: shown.href, ...(shown.tone ? { tone: shown.tone } : {}), wide: shown.kind === 'text' && shown.text.length > 80 }
294
+ }
252
295
  if (column.type === 'boolean') {
253
296
  const yes = stored === true || stored === 1 || stored === '1'
254
297
  return { ...base, value: yes ? 'Yes' : 'No', empty: false, kind: 'boolean', yes }
@@ -270,7 +313,7 @@ function detail(record: ModelRecord, column: ModelColumn, names: ModelRelationNa
270
313
  }
271
314
  const value = String(stored)
272
315
  if (BADGE_COLUMNS.has(column.name) && value.length <= 32)
273
- return { ...base, value: titleCase(value), empty: false, kind: 'badge' }
316
+ return { ...base, value: titleCase(value), empty: false, kind: 'badge', tone: modelBadgeTone(value) }
274
317
  return { ...base, value, empty: false, kind: 'text', wide: value.length > 80 }
275
318
  }
276
319
 
@@ -287,7 +330,7 @@ export function modelRecordSections(record: ModelRecord, names: ModelRelationNam
287
330
  groups.identifiers.push(entry)
288
331
  else if (isDate(column))
289
332
  groups.timestamps.push(entry)
290
- else if (column.type === 'boolean' || column.type === 'number' || BADGE_COLUMNS.has(column.name))
333
+ else if (column.type === 'boolean' || column.type === 'number' || BADGE_COLUMNS.has(column.name) || entry.kind === 'badge')
291
334
  groups.details.push(entry)
292
335
  else
293
336
  groups.information.push(entry)
@@ -552,6 +595,151 @@ export function modelDeleteNotice(name: string, outcome: ModelDeleteOutcome): {
552
595
  return { title: `${name} deleted` }
553
596
  }
554
597
 
598
+ /**
599
+ * The model's own actions one record is offered in one place.
600
+ *
601
+ * Which records an action is for is the server's to say: it sends, per row,
602
+ * the names of the actions that apply, and a row it does not list is offered
603
+ * none. The page only narrows that to where each button belongs.
604
+ */
605
+ export function modelActionsFor(
606
+ actions: ModelCustomAction[] | undefined,
607
+ rowActions: Record<string, string[]> | undefined,
608
+ id: string | number,
609
+ place: 'record' | 'row',
610
+ ): ModelCustomAction[] {
611
+ const offered = rowActions?.[String(id)] ?? []
612
+ return (actions ?? []).filter(action => offered.includes(action.name) && action.places.includes(place))
613
+ }
614
+
615
+ /** The classes of an action's icon: its own, or a bolt for one that names none. */
616
+ export function modelActionIconClass(action: ModelCustomAction): string {
617
+ const tone = action.destructive ? 'text-red-500' : 'text-neutral-500 dark:text-neutral-400'
618
+ return `h-4 w-4 ${tone} ${action.icon || 'i-hugeicons-flash'}`
619
+ }
620
+
621
+ export type ModelActionResult
622
+ = | { ok: true, message: string, redirect: string }
623
+ /**
624
+ * `status` is the refusal's HTTP status, or 0 when no answer came back at
625
+ * all. `errors` are the messages for the input's own fields, when the
626
+ * refusal is about what was typed.
627
+ */
628
+ | { ok: false, error: string, status?: number, errors?: Record<string, string[]> }
629
+
630
+ /** Whether pressing an action's button opens a form: it takes input. */
631
+ export function modelActionAsks(action: ModelCustomAction | null | undefined): boolean {
632
+ return (action?.fields?.length ?? 0) > 0
633
+ }
634
+
635
+ /**
636
+ * What a form's values are sent as: the request body the action's own route
637
+ * would receive, each value the type its rule expects. Nothing here checks
638
+ * them; the action's `validations` do.
639
+ *
640
+ * A field left empty is left out, not sent as null: to a rule, an absent
641
+ * optional field and a null one are different things.
642
+ */
643
+ export function modelActionInput(fields: ModelCreateField[], values: ModelFormValues): Record<string, unknown> {
644
+ const input: Record<string, unknown> = {}
645
+ for (const field of fields) {
646
+ const value = values[field.name]
647
+ if (field.type === 'boolean') {
648
+ input[field.name] = value === true
649
+ continue
650
+ }
651
+ if (typeof value !== 'string' || value === '')
652
+ continue
653
+ if (field.type === 'number') {
654
+ // A rule for a number refuses the digits as text.
655
+ const number = Number(value)
656
+ input[field.name] = Number.isFinite(number) ? number : value
657
+ }
658
+ else if (field.type === 'datetime') {
659
+ const moment = new Date(value)
660
+ input[field.name] = Number.isNaN(moment.getTime()) ? value : moment.toISOString()
661
+ }
662
+ else {
663
+ input[field.name] = value
664
+ }
665
+ }
666
+ return input
667
+ }
668
+
669
+ /**
670
+ * Run one of a model's own actions on a record. A refusal comes back as its
671
+ * reason, in the action's words: "Already shipped."
672
+ *
673
+ * `input` is what the action was told (see {@link modelActionInput}), sent
674
+ * as the body its own route would receive.
675
+ */
676
+ export async function runModelAction(slug: string, id: string | number, name: string, input: Record<string, unknown> = {}): Promise<ModelActionResult> {
677
+ try {
678
+ const result = await dashboardApi<{ ok?: boolean, message?: string, redirect?: string }>(
679
+ `${modelPath(slug)}/${encodeURIComponent(String(id))}/actions/${encodeURIComponent(name)}`,
680
+ { method: 'POST', body: input },
681
+ )
682
+ const redirect = typeof result?.redirect === 'string' && /^\/(?!\/)/.test(result.redirect) ? result.redirect : ''
683
+ return { ok: true, message: typeof result?.message === 'string' ? result.message : '', redirect }
684
+ }
685
+ catch (reason) {
686
+ if (!(reason instanceof DashboardApiError))
687
+ return { ok: false, error: reason instanceof Error ? reason.message : String(reason), status: 0 }
688
+ // The same shape a refused save has: a line for the top of the form, and
689
+ // the action's own message under each field it is about.
690
+ const failure = modelWriteFailure(reason)
691
+ return { ok: false, error: failure.error, status: reason.status, ...(Object.keys(failure.errors).length > 0 ? { errors: failure.errors } : {}) }
692
+ }
693
+ }
694
+
695
+ /**
696
+ * The toast after an action: its name, and what it said came of it. An
697
+ * action that says nothing is still confirmed, so a press is never met with
698
+ * silence.
699
+ */
700
+ export function modelActionNotice(action: ModelCustomAction, result: ModelActionResult): { tone: 'success' | 'error', title: string, detail: string } {
701
+ if (result.ok)
702
+ return { tone: 'success', title: action.label, detail: result.message || 'Done.' }
703
+ return { tone: 'error', title: `${action.label} did not run`, detail: result.error }
704
+ }
705
+
706
+ export type ModelUploadResult = { ok: true, url: string } | { ok: false, error: string }
707
+
708
+ /**
709
+ * Store the file chosen for one of a model's upload fields. Answers with the
710
+ * address it was stored at, which the form then holds as the field's value:
711
+ * nothing about a record changes until the form itself is saved.
712
+ */
713
+ export async function uploadModelFile(slug: string, field: string, file: File): Promise<ModelUploadResult> {
714
+ const formData = new FormData()
715
+ formData.set('field', field)
716
+ formData.set('file', file)
717
+ try {
718
+ const stored = await dashboardApi<{ url?: string }>(`${modelPath(slug)}/uploads`, { method: 'POST', formData })
719
+ return typeof stored?.url === 'string' && stored.url ? { ok: true, url: stored.url } : { ok: false, error: 'The file was stored, but no address came back for it.' }
720
+ }
721
+ catch (reason) {
722
+ return { ok: false, error: reason instanceof Error ? reason.message : String(reason) }
723
+ }
724
+ }
725
+
726
+ /** Whether an address ends like a picture's, so it can be shown as one. */
727
+ export function modelFileIsImage(address: string): boolean {
728
+ return /\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(address)
729
+ }
730
+
731
+ /** The last part of an address: the file's name, for a link to it. */
732
+ export function modelFileName(address: string): string {
733
+ const last = (address.split(/[?#]/)[0] ?? '').split('/').filter(Boolean).pop() ?? address
734
+ try {
735
+ return decodeURIComponent(last)
736
+ }
737
+ catch {
738
+ // Not percent-encoding after all: the name as it is written.
739
+ return last
740
+ }
741
+ }
742
+
555
743
  /** Where the invite page lives, remembering the list to return to. */
556
744
  export function userInviteHref(from?: string): string {
557
745
  return from ? `/data/users/invite?from=${encodeURIComponent(from)}` : '/data/users/invite'
@@ -631,6 +819,8 @@ export interface ModelRelatedColumn {
631
819
  key: string
632
820
  label: string
633
821
  type: 'text' | 'badge' | 'datetime'
822
+ /** How the related model says the value reads. Wins over `type`. */
823
+ format?: ModelFieldDisplay
634
824
  }
635
825
 
636
826
  /**
@@ -654,6 +844,64 @@ export interface ModelRelatedPanel {
654
844
  /** The newest few, each with its `id` and a value per column. */
655
845
  rows: Array<Record<string, unknown>>
656
846
  canCreate: boolean
847
+ /** The related model lets the dashboard edit its rows. */
848
+ canUpdate?: boolean
849
+ /** The related model lets the dashboard delete its rows. */
850
+ canDestroy?: boolean
851
+ /** What "Add" and the pencil ask for: the related model's fields, less the link back here. */
852
+ fields?: ModelCreateField[]
853
+ /** What an edit starts from: each listed row's stored values, by row id. */
854
+ values?: Record<string, Record<string, unknown>>
855
+ }
856
+
857
+ /** A panel's form: a new row for this record, or one of its rows being edited. */
858
+ export interface ModelRelatedEditor {
859
+ panel: ModelRelatedPanel
860
+ /** The row being edited. Null for a new one. */
861
+ id: string | number | null
862
+ }
863
+
864
+ /** The panel's row actions: the eye always, the pencil and the trash where the related model allows. */
865
+ export function modelRelatedRowActions(panel: ModelRelatedPanel): Array<{ action: 'view' | 'edit' | 'delete', label: string }> {
866
+ const one = panel.label.toLowerCase()
867
+ return [
868
+ { action: 'view', label: `View ${one}` },
869
+ ...(panel.canUpdate && (panel.fields?.length ?? 0) > 0 ? [{ action: 'edit' as const, label: `Edit ${one}` }] : []),
870
+ ...(panel.canDestroy ? [{ action: 'delete' as const, label: `Delete ${one}` }] : []),
871
+ ]
872
+ }
873
+
874
+ /** Whether "Add" opens its form on this page. Without fields to ask for, it leaves for the create page. */
875
+ export function modelRelatedAddsHere(panel: ModelRelatedPanel): boolean {
876
+ return panel.canCreate && (panel.fields?.length ?? 0) > 0
877
+ }
878
+
879
+ /**
880
+ * Save a panel's form: a new row pointing at this record, or the changes to
881
+ * one of its rows. One write, through the related model's own endpoint.
882
+ * `changed` is false when an edit changed nothing and so sent nothing.
883
+ */
884
+ export async function saveModelRelated(
885
+ editor: ModelRelatedEditor,
886
+ parentId: string | number,
887
+ values: ModelFormValues,
888
+ initial: ModelFormValues,
889
+ ): Promise<{ ok: true, changed: boolean } | ModelWriteFailure> {
890
+ const fields = editor.panel.fields ?? []
891
+ if (editor.id === null) {
892
+ const parent = Number(parentId)
893
+ const result = await createModelRecord(editor.panel.slug, {
894
+ ...modelFormPayload(fields, values),
895
+ // Which record the new row belongs to is this page's to say, not the form's.
896
+ [editor.panel.field]: Number.isSafeInteger(parent) && parent > 0 ? parent : parentId,
897
+ })
898
+ return result.ok ? { ok: true, changed: true } : result
899
+ }
900
+ const changes = modelFormPayload(fields, values, initial)
901
+ if (Object.keys(changes).length === 0)
902
+ return { ok: true, changed: false }
903
+ const result = await updateModelRecord(editor.panel.slug, editor.id, changes)
904
+ return result.ok ? { ok: true, changed: true } : result
657
905
  }
658
906
 
659
907
  /** The panels of a record's page: who points at it. None when it cannot be asked. */
package/functions/data.ts CHANGED
@@ -65,3 +65,12 @@ const endpointByMode: Record<DataMode, string> = {
65
65
  export async function fetchDashboardData<T>(mode: DataMode): Promise<DashboardDataResponse<T>> {
66
66
  return dashboardApi<DashboardDataResponse<T>>(endpointByMode[mode])
67
67
  }
68
+
69
+ /**
70
+ * A page's row of numbers, without the rows. Users, Teams and Subscribers
71
+ * are listed by the model browser; their pages ask here for the stats alone.
72
+ */
73
+ export async function fetchDashboardStats(mode: DataMode): Promise<DataStats> {
74
+ const answer = await dashboardApi<{ stats?: DataStats }>(`${endpointByMode[mode]}?only=stats`)
75
+ return answer.stats ?? { total: 0 }
76
+ }
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.551",
5
+ "version": "0.75.555",
6
6
  "description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
7
7
  "license": "MIT",
8
8
  "funding": "https://github.com/sponsors/chrisbbreuer",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/defaults",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.551",
5
+ "version": "0.75.555",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/stacksjs/stacks.git",
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "@iconify-json/f7": "^1.2.2",
47
47
  "@iconify-json/hugeicons": "^1.2.35",
48
- "@stacksjs/mobile": "0.75.551",
48
+ "@stacksjs/mobile": "0.75.555",
49
49
  "@stacksjs/sanitizer": "^0.2.859",
50
50
  "@stacksjs/stx": "^0.2.859",
51
- "@stacksjs/strings": "0.75.551",
51
+ "@stacksjs/strings": "0.75.555",
52
52
  "@xterm/addon-fit": "^0.11.0",
53
53
  "@xterm/xterm": "^6.0.0",
54
54
  "ts-qr-codes": "^0.1.8"