@crombolo/data 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,6 +28,6 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.21.0"
31
+ "@crombolo/core": "0.23.0"
32
32
  }
33
33
  }
@@ -340,6 +340,14 @@ export class DocumentRepository {
340
340
  return this.#inTreeLock ? fn() : this.#db.locks.withLock(KINDS[this.kind].lock, fn)
341
341
  }
342
342
 
343
+ /**
344
+ * Runs `fn` under the tree lock in one transaction, with a repository bound to
345
+ * it, so several writes commit together or not at all (story 170).
346
+ */
347
+ async atomically<T>(fn: (repo: DocumentRepository) => Promise<T>): Promise<T> {
348
+ return this.#withTree(() => this.#db.transaction((tx) => fn(this.#child(tx))))
349
+ }
350
+
343
351
  #child(tx: Db): DocumentRepository {
344
352
  return new DocumentRepository(tx, {
345
353
  nodeState: this.#nodeState,
@@ -532,10 +540,41 @@ export class DocumentRepository {
532
540
  [t, this.objectType, this.#db.dialect.boolValue(false)],
533
541
  )
534
542
  const languages = await this.#languages()
535
- const stateId = await visibleStateIdFor(this.#db, this.#nodeState)
536
543
  const typesById = new Map<number, PropertyTypeRow[]>()
544
+ const rowsById = await this.#currentValueRowsFor(rows.map((row) => Number(row.id)))
545
+ const out = []
546
+ for (const row of rows) {
547
+ const typeId = Number(row.content_type_id)
548
+ if (!typesById.has(typeId)) typesById.set(typeId, await this.#propertyTypes(typeId))
549
+ const propertyTypes = typesById.get(typeId) as PropertyTypeRow[]
550
+ out.push({
551
+ id: Number(row.id),
552
+ key: normaliseUuid(String(row.unique_id)),
553
+ name: String(row.draft_name ?? row.text ?? ''),
554
+ contentTypeAlias: String(row.content_type_alias),
555
+ parentId: Number(row.parent_id),
556
+ sortOrder: Number(row.sort_order),
557
+ createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
558
+ updateDate:
559
+ DbDate.fromDb(row.version_date) ?? DbDate.fromDb(row.create_date) ?? new Date(0),
560
+ values:
561
+ propertyTypes.length === 0
562
+ ? []
563
+ : this.#valuesFromRows(rowsById.get(Number(row.id)) ?? [], propertyTypes, languages),
564
+ })
565
+ }
566
+ return out
567
+ }
568
+
569
+ /**
570
+ * The values an editor sees now, per node: the current ones, or, on a node
571
+ * reading an older schema state, the latest at or before it. Read in slices.
572
+ */
573
+ async #currentValueRowsFor(ids: number[]): Promise<Map<number, ValueRow[]>> {
574
+ const t = this.#db.dialect.boolValue(true)
575
+ const stateId = await visibleStateIdFor(this.#db, this.#nodeState)
537
576
  const rowsById = new Map<number, ValueRow[]>()
538
- for (const slice of slices(rows.map((row) => Number(row.id)))) {
577
+ for (const slice of slices(ids)) {
539
578
  if (stateId === undefined) {
540
579
  const current = await this.#db.query(
541
580
  `SELECT id, node_id, event_id, property_type_id, language_id, segment,
@@ -557,28 +596,82 @@ export class DocumentRepository {
557
596
  }
558
597
  }
559
598
  }
560
- const out = []
599
+ return rowsById
600
+ }
601
+
602
+ /**
603
+ * Every document not in the bin as an editor last saved it, published or not,
604
+ * in the published cache's shape: the draft cache behind previewing in an app
605
+ * (story 053). A culture is there once it has a name.
606
+ */
607
+ async loadDrafts(): Promise<PublishedNodeRow[]> {
608
+ const t = this.#db.dialect.boolValue(true)
609
+ const rows = await this.#db.query(
610
+ `SELECT n.id, n.unique_id, n.parent_id, n.level, n.path, n.sort_order, n.create_date, n.text,
611
+ head.text AS draft_name, head.version_date,
612
+ ct.alias AS content_type_alias, c.content_type_id, tpl.alias AS template_alias
613
+ FROM node n
614
+ JOIN content c ON c.node_id = n.id
615
+ JOIN content_type ct ON ct.node_id = c.content_type_id
616
+ JOIN content_version head ON head.node_id = n.id AND head.current = ?
617
+ JOIN document_version hv ON hv.id = head.id
618
+ LEFT JOIN template tpl ON tpl.node_id = hv.template_id
619
+ WHERE n.node_object_type = ? AND n.trashed = ?
620
+ ORDER BY n.level, n.sort_order, n.id`,
621
+ [t, this.objectType, this.#db.dialect.boolValue(false)],
622
+ )
623
+ const ids = rows.map((row) => Number(row.id))
624
+ const languages = await this.#languages()
625
+ const valuesById = await this.#currentValueRowsFor(ids)
626
+ const culturesById = new Map<number, Array<{ isoCode: string; name: string }>>()
627
+ for (const slice of slices(ids)) {
628
+ const cultureRows = await this.#db.query(
629
+ `SELECT dcv.node_id, dcv.name, l.iso_code
630
+ FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
631
+ WHERE dcv.node_id IN (${slice.map(() => '?').join(', ')}) AND dcv.available = ?`,
632
+ [...slice, t],
633
+ )
634
+ for (const row of cultureRows) {
635
+ const id = Number(row.node_id)
636
+ culturesById.set(id, [
637
+ ...(culturesById.get(id) ?? []),
638
+ { isoCode: String(row.iso_code), name: String(row.name ?? '') },
639
+ ])
640
+ }
641
+ }
642
+ const typesById = new Map<number, PropertyTypeRow[]>()
643
+ const drafts: PublishedNodeRow[] = []
561
644
  for (const row of rows) {
562
645
  const typeId = Number(row.content_type_id)
563
- if (!typesById.has(typeId)) typesById.set(typeId, await this.#propertyTypes(typeId))
564
- const propertyTypes = typesById.get(typeId) as PropertyTypeRow[]
565
- out.push({
646
+ if (!typesById.has(typeId))
647
+ // A pending property is never rendered, in a preview no more than on the site.
648
+ typesById.set(
649
+ typeId,
650
+ (await this.#propertyTypes(typeId)).filter((p) => !p.pending),
651
+ )
652
+ const cultures = culturesById.get(Number(row.id)) ?? []
653
+ drafts.push({
566
654
  id: Number(row.id),
567
655
  key: normaliseUuid(String(row.unique_id)),
568
- name: String(row.draft_name ?? row.text ?? ''),
569
- contentTypeAlias: String(row.content_type_alias),
570
656
  parentId: Number(row.parent_id),
657
+ level: Number(row.level),
658
+ path: String(row.path),
571
659
  sortOrder: Number(row.sort_order),
572
- createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
573
- updateDate:
574
- DbDate.fromDb(row.version_date) ?? DbDate.fromDb(row.create_date) ?? new Date(0),
575
- values:
576
- propertyTypes.length === 0
577
- ? []
578
- : this.#valuesFromRows(rowsById.get(Number(row.id)) ?? [], propertyTypes, languages),
660
+ name: String(row.draft_name ?? row.text ?? ''),
661
+ contentTypeAlias: String(row.content_type_alias),
662
+ componentAlias: (row.template_alias as string | null) ?? null,
663
+ createDate: DbDate.fromDb(row.create_date) ?? new Date(),
664
+ updateDate: DbDate.fromDb(row.version_date) ?? DbDate.fromDb(row.create_date) ?? new Date(),
665
+ cultures: cultures.map((c) => c.isoCode),
666
+ names: Object.fromEntries(cultures.map((c) => [c.isoCode, c.name])),
667
+ values: this.#valuesFromRows(
668
+ valuesById.get(Number(row.id)) ?? [],
669
+ typesById.get(typeId) as PropertyTypeRow[],
670
+ languages,
671
+ ),
579
672
  })
580
673
  }
581
- return out
674
+ return drafts
582
675
  }
583
676
 
584
677
  // --------------------------------------------------------------- writes
@@ -1328,6 +1421,8 @@ export class DocumentRepository {
1328
1421
  'UPDATE document SET original_parent_id = NULL, trashed_date = NULL WHERE node_id = ?',
1329
1422
  [node.id],
1330
1423
  )
1424
+ // Nothing published comes back, but a preview's drafts do.
1425
+ await repo.#instructContent(node.key)
1331
1426
  return 'restored' as const
1332
1427
  }),
1333
1428
  )
@@ -2808,3 +2903,12 @@ function parseConfig(raw: unknown): Record<string, unknown> {
2808
2903
  return {}
2809
2904
  }
2810
2905
  }
2906
+
2907
+ /**
2908
+ * The newest version id of anything, which moves on every save: how a node's
2909
+ * draft cache knows it is stale when the save happened on another node.
2910
+ */
2911
+ export async function latestContentVersionId(db: Db): Promise<number> {
2912
+ const rows = await db.query<{ n: number | null }>('SELECT MAX(id) AS n FROM content_version')
2913
+ return Number(rows[0]?.n ?? 0)
2914
+ }
@@ -1,14 +1,18 @@
1
1
  /**
2
- * Content types this CMS ships. "Search & sharing" (`seoFields`) is a
3
- * composition a site opts into with `compositions = ["seoFields"]`: the fields
4
- * the head helper, the sitemap and the editor's preview read.
2
+ * Content types this CMS ships, each a composition a site opts into, such as
3
+ * `compositions = ["seoFields"]`. "Search & sharing" (`seoFields`) holds the
4
+ * fields the head helper, the sitemap and the editor's preview read; "Caching"
5
+ * (`cacheFields`, story 057) how long copies of a page may be kept.
5
6
  *
6
7
  * A **system** type, like the Folder, Image and File media types: ensured at
7
8
  * every boot, exempt from schema retirement, not deletable, alias fixed. A site
8
9
  * may extend it with a file of the same alias and key; the shipped fields stay.
9
10
  */
10
11
  import {
12
+ CACHE_FIELDS_PROPERTIES,
11
13
  type ContentTypeAggregate,
14
+ MENU_ITEM_PROPERTIES,
15
+ MENU_PROPERTIES,
12
16
  SEO_FIELDS_PROPERTIES,
13
17
  SYSTEM_CONTENT_TYPE_KEYS,
14
18
  type SystemPropertyModel,
@@ -22,6 +26,10 @@ export interface BuiltInContentType {
22
26
  name: string
23
27
  description: string
24
28
  icon: string
29
+ /** An element type: the menu types (story 141). */
30
+ isElement?: boolean
31
+ /** Offered for creating in the Library section. */
32
+ allowedInLibrary?: boolean
25
33
  tab: { key: string; name: string; alias: string }
26
34
  properties: readonly SystemPropertyModel[]
27
35
  }
@@ -36,7 +44,48 @@ export const SEO_FIELDS_TYPE: BuiltInContentType = {
36
44
  properties: SEO_FIELDS_PROPERTIES,
37
45
  }
38
46
 
39
- export const SYSTEM_CONTENT_TYPES: readonly BuiltInContentType[] = [SEO_FIELDS_TYPE]
47
+ /** "Caching" (story 057): how long copies of a page may be kept, for the types that want it. */
48
+ export const CACHE_FIELDS_TYPE: BuiltInContentType = {
49
+ key: SYSTEM_CONTENT_TYPE_KEYS.CacheFields,
50
+ alias: 'cacheFields',
51
+ name: 'Caching',
52
+ description: 'How long copies of a page may be kept before they are asked for again.',
53
+ icon: 'icon-timer',
54
+ tab: { key: '0d6e2a49-7c1f-4b85-93a2-6f8e1b4c7d39', name: 'Caching', alias: 'caching' },
55
+ properties: CACHE_FIELDS_PROPERTIES,
56
+ }
57
+
58
+ /** A menu (story 141): made in the Library, named by its alias in templates. */
59
+ export const MENU_TYPE: BuiltInContentType = {
60
+ key: SYSTEM_CONTENT_TYPE_KEYS.Menu,
61
+ alias: 'menu',
62
+ name: 'Menu',
63
+ description: 'Pages and links in the order a navigation shows them.',
64
+ icon: 'icon-navigation',
65
+ isElement: true,
66
+ allowedInLibrary: true,
67
+ tab: { key: '7d1c5a93-0e4b-4f26-8b37-2a9e6c1d5f84', name: 'Menu', alias: 'menu' },
68
+ properties: MENU_PROPERTIES,
69
+ }
70
+
71
+ /** One entry in a menu: a page, media or an address, a label, and items below it. */
72
+ export const MENU_ITEM_TYPE: BuiltInContentType = {
73
+ key: SYSTEM_CONTENT_TYPE_KEYS.MenuItem,
74
+ alias: 'menuItem',
75
+ name: 'Menu item',
76
+ description: 'A page, media item or address in a menu, with any items below it.',
77
+ icon: 'icon-link',
78
+ isElement: true,
79
+ tab: { key: '3a8e2d61-9f5c-4b07-a1d4-6c2b8e0f7a35', name: 'Item', alias: 'item' },
80
+ properties: MENU_ITEM_PROPERTIES,
81
+ }
82
+
83
+ export const SYSTEM_CONTENT_TYPES: readonly BuiltInContentType[] = [
84
+ SEO_FIELDS_TYPE,
85
+ CACHE_FIELDS_TYPE,
86
+ MENU_TYPE,
87
+ MENU_ITEM_TYPE,
88
+ ]
40
89
 
41
90
  export function systemContentTypeAggregate(def: BuiltInContentType): ContentTypeAggregate {
42
91
  return {
@@ -48,8 +97,8 @@ export function systemContentTypeAggregate(def: BuiltInContentType): ContentType
48
97
  allowedAsRoot: false,
49
98
  variesByCulture: false,
50
99
  variesBySegment: false,
51
- isElement: false,
52
- allowedInLibrary: false,
100
+ isElement: def.isElement === true,
101
+ allowedInLibrary: def.allowedInLibrary === true,
53
102
  collectionKey: null,
54
103
  cleanup: {
55
104
  preventCleanup: false,
@@ -8,11 +8,21 @@
8
8
  * deletable, alias fixed. Video, Audio, Article and Vector Graphics are
9
9
  * ordinary types a site owns as files in `schema/media-types/`; `crombolo
10
10
  * init` scaffolds them and deleting one deletes its file.
11
+ *
12
+ * `mediaCacheFields` ("Caching", story 057) is ours: a system type only ever
13
+ * composed into others, so it is never offered as something to make.
11
14
  */
12
- import { type ContentTypeAggregate, normaliseUuid, SYSTEM_MEDIA_TYPE_KEYS } from '@crombolo/core'
15
+ import {
16
+ CACHE_FIELDS_PROPERTIES,
17
+ type ContentTypeAggregate,
18
+ MEDIA_CACHE_FIELDS_TYPE_KEY,
19
+ MEDIA_CACHE_KEEP_FOR_PROPERTY_KEY,
20
+ normaliseUuid,
21
+ SYSTEM_MEDIA_TYPE_KEYS,
22
+ } from '@crombolo/core'
13
23
  import type { Db } from '../database.ts'
14
24
  import { ContentTypeRepository } from '../repositories/content-types.ts'
15
- import { DEFAULT_DATA_TYPES } from './content-seed.ts'
25
+ import { ALL_SEEDED_DATA_TYPES } from './content-seed.ts'
16
26
 
17
27
  export interface BuiltInMediaProperty {
18
28
  key: string
@@ -30,6 +40,8 @@ export interface BuiltInMediaType {
30
40
  icon: string
31
41
  /** Folder, Image and File: undeletable, alias fixed. */
32
42
  system: boolean
43
+ /** Only ever composed into other media types, never made as an item: "Caching" (story 057). */
44
+ composition?: boolean
33
45
  /** A built-in data type alias for the collection view. */
34
46
  collection?: string
35
47
  /** Aliases; Folder allows every built-in, the ones a site has. */
@@ -207,12 +219,30 @@ export const BUILT_IN_MEDIA_TYPES: readonly BuiltInMediaType[] = [
207
219
  pixels('9e4c2b59-6bc6-4648-bb71-b0f45ddbc274', 'umbracoHeight'),
208
220
  ],
209
221
  },
222
+ {
223
+ key: MEDIA_CACHE_FIELDS_TYPE_KEY,
224
+ alias: 'mediaCacheFields',
225
+ name: 'Caching',
226
+ icon: 'icon-timer',
227
+ system: true,
228
+ composition: true,
229
+ allowChildren: [],
230
+ group: { key: '5c8f1a36-0e7b-4d29-9a54-3b6d2e8f1c70', name: 'Caching', alias: 'caching' },
231
+ // Its own key: a property key is unique across every type, document or media.
232
+ properties: CACHE_FIELDS_PROPERTIES.map((p) => ({
233
+ key: MEDIA_CACHE_KEEP_FOR_PROPERTY_KEY,
234
+ alias: p.alias,
235
+ name: p.name,
236
+ dataType: 'keepCopiesFor',
237
+ mandatory: false,
238
+ })),
239
+ },
210
240
  ]
211
241
 
212
242
  export const SYSTEM_MEDIA_TYPES = BUILT_IN_MEDIA_TYPES.filter((t) => t.system)
213
243
 
214
244
  const dataTypeKey = (alias: string): string => {
215
- const found = DEFAULT_DATA_TYPES.find((d) => d.alias === alias)
245
+ const found = ALL_SEEDED_DATA_TYPES.find((d) => d.alias === alias)
216
246
  if (!found) throw new Error(`built-in media types reference unknown data type "${alias}"`)
217
247
  return found.key
218
248
  }
@@ -228,7 +258,7 @@ export function builtInMediaTypeAggregate(
228
258
  name: def.name,
229
259
  description: null,
230
260
  icon: def.icon,
231
- allowedAsRoot: true,
261
+ allowedAsRoot: !def.composition,
232
262
  variesByCulture: false,
233
263
  variesBySegment: false,
234
264
  isElement: false,
@@ -5,7 +5,16 @@
5
5
  * Data type keys are Umbraco's own, so any documentation or example that
6
6
  * references a well-known data type still applies.
7
7
  */
8
- import { ObjectTypes, SystemNodes, ValueStorageType } from '@crombolo/core'
8
+ import {
9
+ KEEP_COPIES_FOR,
10
+ KEEP_COPIES_FOR_DATA_TYPE_KEY,
11
+ MENU_ITEMS_DATA_TYPE_KEY,
12
+ MENU_LINK_DATA_TYPE_KEY,
13
+ ObjectTypes,
14
+ SYSTEM_CONTENT_TYPE_KEYS,
15
+ SystemNodes,
16
+ ValueStorageType,
17
+ } from '@crombolo/core'
9
18
  import type { Db } from '../database.ts'
10
19
  import { DbDate } from '../dialect.ts'
11
20
 
@@ -507,6 +516,34 @@ export async function seedContent(db: Db): Promise<boolean> {
507
516
  * than from the vendored client. Seeded and ensured exactly as Umbraco's are.
508
517
  */
509
518
  export const CROMBOLO_DATA_TYPES: readonly SeedDataType[] = [
519
+ // A menu's items and each item's own (story 141): blocks of the Menu item type.
520
+ {
521
+ key: MENU_ITEMS_DATA_TYPE_KEY,
522
+ alias: 'menuItems',
523
+ name: 'Menu items',
524
+ editorAlias: 'Umbraco.BlockList',
525
+ editorUiAlias: 'Umb.PropertyEditorUi.BlockList',
526
+ dbType: ValueStorageType.Ntext,
527
+ config: { blocks: [{ contentElementTypeKey: SYSTEM_CONTENT_TYPE_KEYS.MenuItem }] },
528
+ },
529
+ {
530
+ key: MENU_LINK_DATA_TYPE_KEY,
531
+ alias: 'menuLink',
532
+ name: 'Menu link',
533
+ editorAlias: 'Umbraco.MultiUrlPicker',
534
+ editorUiAlias: 'Umb.PropertyEditorUi.MultiUrlPicker',
535
+ dbType: ValueStorageType.Ntext,
536
+ config: { minNumber: 0, maxNumber: 1 },
537
+ },
538
+ {
539
+ key: KEEP_COPIES_FOR_DATA_TYPE_KEY,
540
+ alias: 'keepCopiesFor',
541
+ name: 'Keep copies for',
542
+ editorAlias: 'Umbraco.DropDown.Flexible',
543
+ editorUiAlias: 'Umb.PropertyEditorUi.Dropdown',
544
+ dbType: ValueStorageType.Nvarchar,
545
+ config: { multiple: false, items: KEEP_COPIES_FOR.map((choice) => choice.label) },
546
+ },
510
547
  {
511
548
  key: '9c4a7d1e-0100-4b2a-9f31-6d8e2c5a7b40',
512
549
  alias: 'formPicker',