@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,17 +1,20 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
3
  import { Team } from '@stacksjs/orm'
3
4
  import { safeGet } from '../../../../resources/functions/dashboard/data'
4
5
  import { dashboardOperationalError } from '../dashboard-response'
5
- import { dateValue, daysAgoIso, numberValue, textValue } from './data-records'
6
+ import { dateValue, daysAgoIso, numberValue, statsOnly, textValue } from './data-records'
6
7
 
7
8
  export default new Action({
8
9
  name: 'TeamIndexAction',
9
10
  description: 'Returns teams and native team statistics for the dashboard.',
10
11
  method: 'GET',
11
12
  apiResponse: true,
12
- async handle() {
13
+ async handle(request: RequestInstance) {
13
14
  try {
14
- const rows = await Team.orderByDesc('created_at').limit(100).get()
15
+ // The page that shows these numbers lists its rows through the model
16
+ // browser, and asks here for the numbers alone.
17
+ const rows = statsOnly(request) ? [] : await Team.orderByDesc('created_at').limit(100).get()
15
18
  const teams = rows.map(row => ({
16
19
  id: numberValue(safeGet(row, 'id', 0)),
17
20
  name: textValue(safeGet(row, 'name'), 'Unnamed team'),
@@ -1,17 +1,20 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
3
  import { anonymizedRows, GDPR_SUBJECT_MODEL, User } from '@stacksjs/orm'
3
4
  import { safeGet } from '../../../../resources/functions/dashboard/data'
4
5
  import { dashboardOperationalError } from '../dashboard-response'
5
- import { dateValue, daysAgoIso, numberValue, textValue } from './data-records'
6
+ import { dateValue, daysAgoIso, numberValue, statsOnly, textValue } from './data-records'
6
7
 
7
8
  export default new Action({
8
9
  name: 'UserIndexAction',
9
10
  description: 'Returns a safe projection of users and native registration statistics.',
10
11
  method: 'GET',
11
12
  apiResponse: true,
12
- async handle() {
13
+ async handle(request: RequestInstance) {
13
14
  try {
14
- const rows = await User.orderByDesc('created_at').limit(100).get()
15
+ // The page that shows these numbers lists its rows through the model
16
+ // browser, and asks here for the numbers alone.
17
+ const rows = statsOnly(request) ? [] : await User.orderByDesc('created_at').limit(100).get()
15
18
  // An account erased under the app's data-subject rules stays in the
16
19
  // table with its personal details replaced. Listed as it is stored it
17
20
  // reads "[erased] / erased-13", which looks like corrupt data, so each
@@ -26,3 +26,15 @@ export function createdWithinDays(value: string, days: number, now = Date.now())
26
26
  export function daysAgoIso(days: number, now = Date.now()): string {
27
27
  return new Date(now - days * 24 * 60 * 60 * 1000).toISOString()
28
28
  }
29
+
30
+ /**
31
+ * Whether a data endpoint was asked for its numbers alone (`?only=stats`).
32
+ *
33
+ * Users, Teams and Subscribers are listed by the model browser, which pages
34
+ * and searches every row. Their pages still open with a row of stats, and
35
+ * those come from here: without this each page load would also read a
36
+ * hundred rows it never draws.
37
+ */
38
+ export function statsOnly(request: { get?: (key: string) => unknown } | null | undefined): boolean {
39
+ return request?.get?.('only') === 'stats'
40
+ }
@@ -0,0 +1,77 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { Action } from '@stacksjs/actions/runtime'
3
+ import { anonymizedRows } from '@stacksjs/orm'
4
+ import { resolveActionHandler, response } from '@stacksjs/router'
5
+ import { safeGet } from '../../../../resources/functions/dashboard/data'
6
+ import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
7
+ import { dashboardOperationalError } from '../dashboard-response'
8
+ import { modelActionApplies, modelActionOutcome, modelActions } from './model-actions'
9
+ import { humanizeIdentifier, isErasureSubject, isValidModelSlug, modelSchemaColumns, parseRowId, slugToPascal } from './model-write'
10
+
11
+ /**
12
+ * `POST /api/dashboard/models/{dashboardModel}/{id}/actions/{dashboardAction}`.
13
+ *
14
+ * Runs one of the actions a model lists under `dashboard.actions` on one of
15
+ * its records. The action is the app's own, under `app/Actions`, and it runs
16
+ * as its own route would: this request is handed to it, so it reads the
17
+ * record's id with `request.getParam('id')` exactly as it would behind
18
+ * `/orders/{id}/ship`, and its `validations`, `authorize` and `before` apply.
19
+ *
20
+ * The other two parameters carry long names on purpose. Route parameters are
21
+ * part of an action's input, and a `slug` or a `name` here would be read by
22
+ * an action that validates a field of that name.
23
+ *
24
+ * Only what the model declares can be run, only on a record that exists, and
25
+ * only when the record meets the action's `when`: the page hides the button
26
+ * for the others, and this is what holds if it is asked anyway.
27
+ */
28
+ export default new Action({
29
+ name: 'Dashboard Model Action Run',
30
+ description: 'Runs one of the actions a model lists under dashboard.actions on one of its records.',
31
+ method: 'POST',
32
+ apiResponse: true,
33
+ async handle(request: RequestInstance) {
34
+ const slug = String(request.getParam('dashboardModel') ?? '')
35
+ if (!isValidModelSlug(slug))
36
+ return response.json({ message: 'Model slug must be lowercase kebab-case.' }, 400)
37
+ const id = parseRowId(request.getParam('id'))
38
+ if (id === null)
39
+ return response.json({ message: 'A numeric row id is required.' }, 400)
40
+
41
+ const modelName = slugToPascal(slug)
42
+ const name = String(request.getParam('dashboardAction') ?? '')
43
+ let Model: any
44
+ let row: unknown
45
+ try {
46
+ Model = await resolveDashboardModel(modelName)
47
+ if (!Model || typeof Model.find !== 'function')
48
+ return response.json({ message: `No ORM model named ${modelName}.` }, 404)
49
+ row = await Model.find(id)
50
+ }
51
+ catch (error) {
52
+ return dashboardOperationalError(error, `${modelName} ${id} could not be loaded.`, 'ModelActionRunAction.load')
53
+ }
54
+
55
+ const action = (await modelActions(Model, modelName)).find(candidate => candidate.name === name)
56
+ if (!action)
57
+ return response.json({ message: `${modelName} has no dashboard action named '${name}'.` }, 404)
58
+ if (!row)
59
+ return response.json({ message: `${modelName} ${id} not found.` }, 404)
60
+
61
+ const record = humanizeIdentifier(modelName).toLowerCase()
62
+ // An erased account is placeholders: there is nobody left to act on.
63
+ if (isErasureSubject(Model)) {
64
+ const stored = Object.fromEntries(modelSchemaColumns(Model).map(column => [column, safeGet(row, column, null)]))
65
+ const [erased] = await anonymizedRows(modelName, [stored]).catch(() => [false])
66
+ if (erased)
67
+ return response.json({ message: `This ${record} was anonymized, so "${action.label}" has nothing to act on.` }, 409)
68
+ }
69
+ if (!modelActionApplies(action, row))
70
+ return response.json({ message: `"${action.label}" is not available for this ${record} as it is now.` }, 409)
71
+
72
+ // Not caught: what the action throws is answered by this route the way
73
+ // the action's own route would answer it, status and message included.
74
+ const handler = await resolveActionHandler(action.handler)
75
+ return modelActionOutcome(await handler(request), action.label)
76
+ },
77
+ })
@@ -0,0 +1,42 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { Action } from '@stacksjs/actions/runtime'
3
+ import { response } from '@stacksjs/router'
4
+ import { sanitize } from '@stacksjs/sanitizer'
5
+ import { dashboardOperationalError } from '../dashboard-response'
6
+
7
+ /** The most Markdown a preview takes: what the largest text column is asked to hold. */
8
+ const MAX_MARKDOWN = 100_000
9
+
10
+ /** Markdown as the HTML it reads as: the parser Stacks content uses, then sanitized. */
11
+ export function renderMarkdownPreview(markdown: string): string {
12
+ return sanitize(Bun.markdown.html(markdown), 'markdown')
13
+ }
14
+
15
+ /**
16
+ * `POST /api/dashboard/markdown`.
17
+ *
18
+ * How a field's Markdown reads, for the preview beside its editor
19
+ * (`dashboard.fields.<name>.input: 'markdown'`). Rendered here and not in the
20
+ * browser so the preview is the parser Stacks content is rendered with, and
21
+ * sanitized: the page shows it in a frame that runs no script either way.
22
+ * Nothing is stored.
23
+ */
24
+ export default new Action({
25
+ name: 'Dashboard Markdown Preview',
26
+ description: 'Renders Markdown to sanitized HTML for a form\'s preview.',
27
+ method: 'POST',
28
+ apiResponse: true,
29
+ async handle(request: RequestInstance) {
30
+ const text = request.get('text', '')
31
+ if (typeof text !== 'string')
32
+ return response.json({ message: 'The text to preview must be text.' }, 422)
33
+ if (text.length > MAX_MARKDOWN)
34
+ return response.json({ message: 'That is too long to preview.' }, 422)
35
+ try {
36
+ return { html: renderMarkdownPreview(text) }
37
+ }
38
+ catch (error) {
39
+ return dashboardOperationalError(error, 'The preview could not be made.', 'ModelMarkdownAction', 500)
40
+ }
41
+ },
42
+ })
@@ -1,18 +1,22 @@
1
1
  import { hiddenModelColumns } from '../../../../resources/functions/dashboard/model-columns'
2
2
  import type { RequestInstance } from '@stacksjs/types'
3
3
  import { Action } from '@stacksjs/actions/runtime'
4
- import { anonymizedRows } from '@stacksjs/orm'
4
+ import { anonymizedRows, personalColumns } from '@stacksjs/orm'
5
5
  import { response as routerResponse } from '@stacksjs/router'
6
6
  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
+ import { type ModelCustomAction, modelActionApplies, modelActions, publicModelAction } from './model-actions'
10
+ import { modelFormFields, reachableRelations } from './model-forms'
9
11
  import { isUnmigratedTable } from './model-migration'
10
12
  import { recordNames } from './model-options'
11
- import { belongsToRelations } from './model-relations'
12
- import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelCreateFields, modelListColumns, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
13
+ import type { ModelFieldDisplay } from './model-fields'
14
+ import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelColumnDisplay, modelColumnLabel, modelFieldProblems, modelListColumns, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
13
15
 
14
16
  /** Models already told, this process, that `dashboard.columns` names a column they lack. */
15
17
  const warnedColumns = new Set<string>()
18
+ /** Models already told, this process, what is wrong with their `dashboard.fields`. */
19
+ const warnedFields = new Set<string>()
16
20
 
17
21
  /**
18
22
  * `GET /api/dashboard/models/{slug}` (stacksjs/stacks#1838).
@@ -41,6 +45,8 @@ interface ColumnMeta {
41
45
  label: string
42
46
  /** Coarse kind used by the table to pick an alignment and a filter control. */
43
47
  type: 'number' | 'boolean' | 'date' | 'json' | 'text'
48
+ /** How the model says the value is shown (`dashboard.fields`): money, a size, a link. */
49
+ format?: ModelFieldDisplay
44
50
  }
45
51
 
46
52
  interface ResponseShape {
@@ -75,6 +81,16 @@ interface ResponseShape {
75
81
  updateColumns: string[]
76
82
  /** Rows whose personal details erasure has replaced with placeholders (the subject model only). */
77
83
  anonymizedIds?: Array<number | string>
84
+ /**
85
+ * The columns erasure replaces, of the ones the page is sent: in an
86
+ * anonymized row they hold placeholders (`[erased]`), not a name anyone
87
+ * typed, and the page says so instead of showing them.
88
+ */
89
+ anonymizedColumns?: string[]
90
+ /** What the model lets an operator do to a record beyond editing it: its `dashboard.actions`. */
91
+ actions: ModelCustomAction[]
92
+ /** Which of those each row on this page is offered, by row id. A row with none is left out. */
93
+ rowActions: Record<string, string[]>
78
94
  /** False when the model's table does not exist yet: `./buddy migrate` creates it. */
79
95
  migrated: boolean
80
96
  error: string | null
@@ -232,6 +248,8 @@ export default new Action({
232
248
  listColumns: [],
233
249
  relationNames: {},
234
250
  updateColumns: [],
251
+ actions: [],
252
+ rowActions: {},
235
253
  migrated: true,
236
254
  error: null,
237
255
  }
@@ -246,6 +264,10 @@ export default new Action({
246
264
  if (!Model || typeof Model.where !== 'function')
247
265
  return routerResponse.json({ message: `No ORM model named ${modelName}.` }, 404)
248
266
 
267
+ // The rows as the model returned them, hidden columns included: an
268
+ // action's `when` may be about a column the page is never sent.
269
+ let stored: unknown[] = []
270
+
249
271
  try {
250
272
  response.tableName = String(Model.table || tableName)
251
273
  const probe = await Model.orderByDesc('id').take(1).get() as Array<Record<string, unknown>>
@@ -307,6 +329,7 @@ export default new Action({
307
329
  .take(perPage)
308
330
  .get() as Array<Record<string, unknown>>
309
331
 
332
+ stored = Array.isArray(rows) ? rows : []
310
333
  response.rows = (Array.isArray(rows) ? rows : []).map((row) => {
311
334
  const flat: Record<string, unknown> = {}
312
335
  for (const col of response.columns)
@@ -323,6 +346,10 @@ export default new Action({
323
346
  return [] as boolean[]
324
347
  })
325
348
  response.anonymizedIds = response.rows.filter((_row, index) => erased[index] === true).map(row => row.id as number | string)
349
+ if (response.anonymizedIds.length > 0) {
350
+ const personal = await personalColumns(modelName).catch(() => [] as string[])
351
+ response.anonymizedColumns = personal.filter(column => response.columns.includes(column))
352
+ }
326
353
  }
327
354
  }
328
355
  catch (error) {
@@ -339,29 +366,31 @@ export default new Action({
339
366
  // it points at. One whose feature is off, or that is kept out of the
340
367
  // dashboard, stays the plain id it was.
341
368
  const reachable = new Set<string>()
342
- for (const relation of belongsToRelations(Model)) {
343
- const related = await resolveDashboardModel(relation.model).catch(() => null)
344
- if (related && typeof related.where === 'function') {
345
- reachable.add(relation.model)
346
- response.relations[relation.column] = { model: relation.model, slug: relation.slug, label: humanizeIdentifier(relation.model) }
347
- }
369
+ for (const relation of await reachableRelations(Model)) {
370
+ reachable.add(relation.model)
371
+ response.relations[relation.column] = { model: relation.model, slug: relation.slug, label: humanizeIdentifier(relation.model) }
348
372
  }
349
- const formFields = (): ModelCreateField[] => modelCreateFields(Model).map((field) => {
350
- if (field.type !== 'relation' || reachable.has(field.relation?.model ?? ''))
351
- return field
352
- const { relation: _unreachable, ...plain } = field
353
- return { ...plain, type: 'number', label: humanizeIdentifier(field.name) }
354
- })
373
+ const formFields = (): ModelCreateField[] => modelFormFields(Model, reachable)
355
374
  response.createFields = response.writeCapabilities.create ? formFields() : []
356
375
  response.updateColumns = response.writeCapabilities.update ? modelWritableColumns(Model) : []
357
376
  response.updateFields = response.writeCapabilities.update ? formFields() : []
358
377
  response.displayColumns = response.columns.filter(col => !col.startsWith('_'))
359
- response.columnMeta = response.displayColumns.map(name => ({
360
- name,
361
- // "Team", not "Team ID": the column shows which team.
362
- label: response.relations[name]?.label ?? humanizeIdentifier(name),
363
- type: typeForColumn(name, response.rows.map(r => r[name])),
364
- }))
378
+ response.columnMeta = response.displayColumns.map((name) => {
379
+ const format = modelColumnDisplay(Model, name)
380
+ return {
381
+ name,
382
+ // The model's own word for it, else "Team" and not "Team ID" (the
383
+ // column shows which team), else the name in words.
384
+ label: modelColumnLabel(Model, name, response.relations[name]?.label),
385
+ type: typeForColumn(name, response.rows.map(r => r[name])),
386
+ ...(format ? { format } : {}),
387
+ }
388
+ })
389
+ if (!warnedFields.has(modelName)) {
390
+ warnedFields.add(modelName)
391
+ for (const problem of modelFieldProblems(Model, response.columns))
392
+ console.warn(`[dashboard] ${modelName} dashboard.fields: ${problem}. It is ignored.`)
393
+ }
365
394
 
366
395
  const list = modelListColumns(Model, response.displayColumns)
367
396
  response.listColumns = list.columns
@@ -380,6 +409,19 @@ export default new Action({
380
409
  if (ids.length > 0)
381
410
  response.relationNames[column] = Object.fromEntries(await recordNames(relation.model, ids))
382
411
  }
412
+
413
+ // The model's own actions, and the rows each is for. Decided here, where
414
+ // the whole row is, so the page never has to be sent the rule. An erased
415
+ // account is offered none: there is nobody left to act on.
416
+ const actions = await modelActions(Model, modelName)
417
+ response.actions = actions.map(publicModelAction)
418
+ const erased = new Set((response.anonymizedIds ?? []).map(String))
419
+ for (const [index, row] of stored.entries()) {
420
+ const id = String(response.rows[index]?.id ?? '')
421
+ const offered = id && !erased.has(id) ? actions.filter(action => modelActionApplies(action, row)).map(action => action.name) : []
422
+ if (offered.length > 0)
423
+ response.rowActions[id] = offered
424
+ }
383
425
  response.searchable = response.columnMeta.filter(c => c.type === 'text').map(c => c.name)
384
426
  response.lastPage = Math.max(1, Math.ceil(response.totalCount / perPage))
385
427
 
@@ -0,0 +1,83 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import type { UploadedFileLike } from '@stacksjs/storage'
3
+ import { Action } from '@stacksjs/actions/runtime'
4
+ import { response } from '@stacksjs/router'
5
+ import { uploadDashboardFiles } from '../Content/file-manager'
6
+ import { dashboardFileFailure } from '../Content/file-response'
7
+ import { modelFormFields, reachableRelations } from './model-forms'
8
+ import { describeAccept, MODEL_UPLOAD_BYTES, uploadAccepts, uploadDirectory } from './model-upload'
9
+ import { modelWriteCapabilities, resolveWritableModel } from './model-write'
10
+
11
+ /** The file's bytes, however the request handed it over. */
12
+ async function uploadedBytes(file: UploadedFileLike): Promise<Uint8Array | undefined> {
13
+ if (typeof file.bytes === 'function')
14
+ return await file.bytes()
15
+ if (typeof file.arrayBuffer === 'function')
16
+ return new Uint8Array(await file.arrayBuffer())
17
+ if (file.buffer)
18
+ return file.buffer instanceof ArrayBuffer ? new Uint8Array(file.buffer) : new Uint8Array(file.buffer)
19
+ return undefined
20
+ }
21
+
22
+ /**
23
+ * `POST /api/dashboard/models/{slug}/uploads`.
24
+ *
25
+ * Stores the file chosen for one of a model's fields and answers with its
26
+ * address, which the form then holds as the field's value. Nothing about any
27
+ * record changes here: the address is written when the form is saved, by the
28
+ * endpoint that saves the rest of it.
29
+ *
30
+ * It only takes a file for a field the model asks for as one
31
+ * (`dashboard.fields.<name>.input: 'upload'`), of a kind that field accepts,
32
+ * on a model the dashboard may write. The file goes through the pipeline the
33
+ * Files page uses, so it is listed there, and gets a generated name, so two
34
+ * people uploading `photo.png` do not meet.
35
+ */
36
+ export default new Action({
37
+ name: 'Dashboard Model Upload',
38
+ description: 'Stores the file chosen for one of a model\'s upload fields and returns its address.',
39
+ method: 'POST',
40
+ apiResponse: true,
41
+ async handle(request: RequestInstance) {
42
+ const resolved = await resolveWritableModel(request.getParam('slug'))
43
+ if ('error' in resolved)
44
+ return response.json({ message: resolved.error }, resolved.status)
45
+ const { Model, modelName } = resolved
46
+ const capabilities = modelWriteCapabilities(Model)
47
+ if (!capabilities.create && !capabilities.update)
48
+ return response.json({ message: `${modelName} records cannot be written from the dashboard, so there is nothing to upload a file for.` }, 405)
49
+
50
+ const name = String(request.get('field', '') ?? '')
51
+ const reachable = new Set((await reachableRelations(Model)).map(relation => relation.model))
52
+ const field = modelFormFields(Model, reachable).find(candidate => candidate.name === name && candidate.type === 'upload')
53
+ if (!field)
54
+ return response.json({ message: name ? `${modelName} does not take an uploaded file for '${name}'.` : 'Say which field the file is for.' }, 422)
55
+
56
+ const file = request.file('file') as (UploadedFileLike & { size?: number }) | null | undefined
57
+ if (!file)
58
+ return response.json({ message: 'Choose a file.', fields: { [field.name]: 'Choose a file.' } }, 422)
59
+ if (Number(file.size || 0) > MODEL_UPLOAD_BYTES)
60
+ return response.json({ message: 'The file must be 10 MB or smaller.', fields: { [field.name]: 'The file must be 10 MB or smaller.' } }, 422)
61
+ // By what the file is, not what it was sent as: its first bytes say.
62
+ const bytes = await uploadedBytes(file)
63
+ if (!uploadAccepts(field.accept, { type: file.mimeType ?? file.mimetype, name: file.name ?? file.originalName, bytes })) {
64
+ const message = `${field.label} takes ${describeAccept(field.accept ?? '')}.`
65
+ return response.json({ message, fields: { [field.name]: message } }, 422)
66
+ }
67
+
68
+ try {
69
+ const [stored] = await uploadDashboardFiles({
70
+ disk: 'public',
71
+ path: uploadDirectory(String(Model.table || modelName), field.name.replace(/([a-z\d])([A-Z])/g, '$1_$2')),
72
+ files: [file],
73
+ filename: 'uuid',
74
+ })
75
+ if (!stored)
76
+ throw new Error('The upload answered with no file.')
77
+ return response.json({ url: stored.url, path: stored.path, size: stored.size }, 201)
78
+ }
79
+ catch (error) {
80
+ return dashboardFileFailure(error, 'The file could not be stored.', 'ModelUploadAction')
81
+ }
82
+ },
83
+ })