@crombolo/data 0.69.1 → 0.70.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.
@@ -13,6 +13,7 @@
13
13
  import {
14
14
  type ContentTypeAggregate,
15
15
  ContentVariation,
16
+ ENVIRONMENT_VARIATION,
16
17
  normaliseUuid,
17
18
  ObjectTypes,
18
19
  type PropertyGroupModel,
@@ -23,6 +24,7 @@ import {
23
24
  SystemNodes,
24
25
  variationFlags,
25
26
  variesByCulture,
27
+ variesByEnvironment,
26
28
  variesBySegment,
27
29
  } from '@crombolo/core'
28
30
  import type { Db } from '../database.ts'
@@ -30,6 +32,7 @@ import { DbDate, fromDbBool } from '../dialect.ts'
30
32
  import { pendingUntil } from '../pending.ts'
31
33
  import type { NodeSchemaState } from '../schema-state.ts'
32
34
  import { queueContentTypesForSearch, queueEverythingForSearch } from '../search.ts'
35
+ import { type WorkspaceScope, workspaceRowKey } from '../workspace-keys.ts'
33
36
  import { NodeRepository } from './nodes.ts'
34
37
 
35
38
  const GROUP_TYPE_NAMES = ['Group', 'Tab'] as const
@@ -112,11 +115,37 @@ export const CONTENT_TYPE_OBJECT_TYPES: Record<
112
115
  member: { item: ObjectTypes.MemberType, container: ObjectTypes.MemberTypeContainer },
113
116
  }
114
117
 
118
+ /** The object type a workspace's copy of each kind carries (story 376). */
119
+ export const WORKSPACE_TYPE_OBJECT_TYPES: Record<ContentTypeKind, string> = {
120
+ document: ObjectTypes.WorkspaceDocumentType,
121
+ media: ObjectTypes.WorkspaceMediaType,
122
+ member: ObjectTypes.WorkspaceMemberType,
123
+ }
124
+
115
125
  export interface ContentTypeRepositoryOptions {
116
126
  /** The state this node runs at; elements newer than it are marked pending. */
117
127
  nodeState?: NodeSchemaState
118
128
  /** Which kind of type this repository reads and writes. Default document. */
119
129
  kind?: ContentTypeKind
130
+ /**
131
+ * A workspace's view (story 376): its copies of types where it has them, and
132
+ * Shared's otherwise, each under the key it stands for.
133
+ */
134
+ workspace?: WorkspaceScope
135
+ /** Internal: rows written as this workspace's copies, under their stored keys. */
136
+ copiesOf?: number
137
+ }
138
+
139
+ /** A type's row as a workspace's listing merges it over Shared's. */
140
+ interface ListedType {
141
+ key: string
142
+ alias: string
143
+ name: string
144
+ allowAtRoot: boolean
145
+ isElement: boolean
146
+ allowInLibrary: boolean
147
+ siteSettings: boolean
148
+ seo: unknown
120
149
  }
121
150
 
122
151
  export class ContentTypeRepository {
@@ -125,13 +154,283 @@ export class ContentTypeRepository {
125
154
  #nodeState: NodeSchemaState | undefined
126
155
  #objectType: string
127
156
  #kind: ContentTypeKind
157
+ #workspace: WorkspaceScope | undefined
158
+ #copiesOf: number | undefined
128
159
 
129
160
  constructor(db: Db, options: ContentTypeRepositoryOptions = {}) {
130
161
  this.#db = db
131
162
  this.#nodes = new NodeRepository(db)
132
163
  this.#nodeState = options.nodeState
133
164
  this.#kind = options.kind ?? 'document'
134
- this.#objectType = CONTENT_TYPE_OBJECT_TYPES[this.#kind].item
165
+ this.#workspace = options.workspace
166
+ this.#copiesOf = options.copiesOf
167
+ this.#objectType =
168
+ this.#copiesOf === undefined
169
+ ? CONTENT_TYPE_OBJECT_TYPES[this.#kind].item
170
+ : WORKSPACE_TYPE_OBJECT_TYPES[this.#kind]
171
+ }
172
+
173
+ /** The same repository in a workspace's view (undefined: Shared's). */
174
+ inWorkspace(workspace: WorkspaceScope | undefined): ContentTypeRepository {
175
+ return new ContentTypeRepository(this.#db, {
176
+ nodeState: this.#nodeState,
177
+ kind: this.#kind,
178
+ ...(workspace ? { workspace } : {}),
179
+ })
180
+ }
181
+
182
+ // ---------------------------------------------------------------- workspaces (story 376)
183
+
184
+ #shared(db: Db = this.#db): ContentTypeRepository {
185
+ return new ContentTypeRepository(db, { nodeState: this.#nodeState, kind: this.#kind })
186
+ }
187
+
188
+ #copies(db: Db = this.#db): ContentTypeRepository {
189
+ return new ContentTypeRepository(db, {
190
+ nodeState: this.#nodeState,
191
+ kind: this.#kind,
192
+ copiesOf: (this.#workspace as WorkspaceScope).id,
193
+ })
194
+ }
195
+
196
+ #stored(key: string): string {
197
+ return workspaceRowKey((this.#workspace as WorkspaceScope).key, normaliseUuid(key))
198
+ }
199
+
200
+ /** The workspace's copy of a type, live or retired, by the key it stands for. */
201
+ async #copyOf(key: string): Promise<{ nodeId: number; retired: boolean } | undefined> {
202
+ const rows = await this.#db.q
203
+ .selectFrom('content_type as ct')
204
+ .innerJoin('node as n', 'n.id', 'ct.node_id')
205
+ .select(['ct.node_id', 'ct.retired_at'])
206
+ .where('n.unique_id', '=', this.#stored(key))
207
+ .where('ct.workspace_id', '=', (this.#workspace as WorkspaceScope).id)
208
+ .execute()
209
+ const row = rows[0]
210
+ return row ? { nodeId: Number(row.node_id), retired: row.retired_at !== null } : undefined
211
+ }
212
+
213
+ /**
214
+ * The node a type is read from in the workspace: its copy where it has one, or
215
+ * Shared's. Takes a node id, which a page's `content_type_id` is.
216
+ */
217
+ async readNodeId(nodeId: number): Promise<number> {
218
+ if (!this.#workspace) return nodeId
219
+ const node = await this.#nodes.byId(nodeId)
220
+ if (!node || node.objectType !== CONTENT_TYPE_OBJECT_TYPES[this.#kind].item) return nodeId
221
+ return (await this.#copyOf(node.key))?.nodeId ?? nodeId
222
+ }
223
+
224
+ /** Every type the workspace sees: its live copies over Shared's, each by the key it stands for. */
225
+ async #listed(): Promise<ListedType[]> {
226
+ const workspace = this.#workspace as WorkspaceScope
227
+ const columns = [
228
+ 'ct.alias',
229
+ 'n.text',
230
+ 'ct.allow_at_root',
231
+ 'ct.is_element',
232
+ 'ct.allow_in_library',
233
+ 'ct.site_settings',
234
+ 'ct.seo',
235
+ 'ct.retired_at',
236
+ ] as const
237
+ const toListed = (key: string, row: Record<string, unknown>): ListedType => ({
238
+ key: normaliseUuid(key),
239
+ alias: String(row.alias),
240
+ name: String(row.text ?? ''),
241
+ allowAtRoot: fromDbBool(row.allow_at_root),
242
+ isElement: fromDbBool(row.is_element),
243
+ allowInLibrary: fromDbBool(row.allow_in_library),
244
+ siteSettings: fromDbBool(row.site_settings),
245
+ seo: row.seo,
246
+ })
247
+ const copies = await this.#db.q
248
+ .selectFrom('content_type as ct')
249
+ .innerJoin('node as n', 'n.id', 'ct.node_id')
250
+ .select([...columns, 'ct.origin_key'])
251
+ .where('ct.workspace_id', '=', workspace.id)
252
+ .where('n.node_object_type', '=', WORKSPACE_TYPE_OBJECT_TYPES[this.#kind])
253
+ .execute()
254
+ const copied = new Set(copies.map((row) => normaliseUuid(String(row.origin_key))))
255
+ const shared = await this.#db.q
256
+ .selectFrom('content_type as ct')
257
+ .innerJoin('node as n', 'n.id', 'ct.node_id')
258
+ .select([...columns, 'n.unique_id'])
259
+ .where('ct.retired_at', 'is', null)
260
+ .where('n.node_object_type', '=', CONTENT_TYPE_OBJECT_TYPES[this.#kind].item)
261
+ .execute()
262
+ return [
263
+ ...copies
264
+ .filter((row) => row.retired_at === null)
265
+ .map((row) => toListed(String(row.origin_key), row)),
266
+ ...shared
267
+ .filter((row) => !copied.has(normaliseUuid(String(row.unique_id))))
268
+ .map((row) => toListed(String(row.unique_id), row)),
269
+ ].sort((a, b) => a.name.localeCompare(b.name))
270
+ }
271
+
272
+ /** Keys as stored, back to the keys they stand for. */
273
+ async #origins(keys: readonly string[]): Promise<Map<string, string>> {
274
+ const out = new Map<string, string>()
275
+ const wanted = [...new Set(keys.map(normaliseUuid))]
276
+ if (wanted.length === 0) return out
277
+ const typeRows = await this.#db.q
278
+ .selectFrom('content_type as t')
279
+ .innerJoin('node as n', 'n.id', 't.node_id')
280
+ .select(['n.unique_id', 't.origin_key'])
281
+ .where('n.unique_id', 'in', wanted)
282
+ .where('t.origin_key', 'is not', null)
283
+ .execute()
284
+ const dataTypeRows = await this.#db.q
285
+ .selectFrom('data_type as t')
286
+ .innerJoin('node as n', 'n.id', 't.node_id')
287
+ .select(['n.unique_id', 't.origin_key'])
288
+ .where('n.unique_id', 'in', wanted)
289
+ .where('t.origin_key', 'is not', null)
290
+ .execute()
291
+ for (const row of [...typeRows, ...dataTypeRows])
292
+ out.set(normaliseUuid(String(row.unique_id)), normaliseUuid(String(row.origin_key)))
293
+ for (const table of ['property_type', 'property_type_group'] as const)
294
+ for (const row of await this.#db.q
295
+ .selectFrom(table)
296
+ .select(['unique_id', 'origin_key'])
297
+ .where('unique_id', 'in', wanted)
298
+ .where('origin_key', 'is not', null)
299
+ .execute())
300
+ out.set(normaliseUuid(String(row.unique_id)), normaliseUuid(String(row.origin_key)))
301
+ return out
302
+ }
303
+
304
+ /** A copy as the workspace reads it: every key the one it stands for. */
305
+ async #asRead(stored: ContentTypeAggregate): Promise<ContentTypeAggregate> {
306
+ const origins = await this.#origins([
307
+ stored.key,
308
+ ...stored.containers.flatMap((c) => [c.key, ...(c.parentKey ? [c.parentKey] : [])]),
309
+ ...stored.properties.flatMap((p) => [p.key, p.dataTypeKey]),
310
+ ...stored.compositions.map((c) => c.contentTypeKey),
311
+ ...stored.allowedContentTypes.map((c) => c.contentTypeKey),
312
+ ])
313
+ const back = (key: string) => origins.get(normaliseUuid(key)) ?? key
314
+ return {
315
+ ...stored,
316
+ key: back(stored.key),
317
+ containers: stored.containers.map((c) => ({
318
+ ...c,
319
+ key: back(c.key),
320
+ parentKey: c.parentKey ? back(c.parentKey) : null,
321
+ })),
322
+ properties: stored.properties.map((p) => ({
323
+ ...p,
324
+ key: back(p.key),
325
+ dataTypeKey: back(p.dataTypeKey),
326
+ containerKey: p.containerKey ? back(p.containerKey) : null,
327
+ })),
328
+ compositions: stored.compositions.map((c) => ({
329
+ ...c,
330
+ contentTypeKey: back(c.contentTypeKey),
331
+ })),
332
+ allowedContentTypes: stored.allowedContentTypes.map((c) => ({
333
+ ...c,
334
+ contentTypeKey: back(c.contentTypeKey),
335
+ })),
336
+ }
337
+ }
338
+
339
+ /** A type as the workspace saves it: its own keys stored, references to what it copied too. */
340
+ async #asStored(db: Db, aggregate: ContentTypeAggregate): Promise<ContentTypeAggregate> {
341
+ const workspace = this.#workspace as WorkspaceScope
342
+ const copied = async (table: 'content_type' | 'data_type', key: string) => {
343
+ const stored = this.#stored(key)
344
+ const rows =
345
+ table === 'content_type'
346
+ ? await db.q
347
+ .selectFrom('content_type as t')
348
+ .innerJoin('node as n', 'n.id', 't.node_id')
349
+ .select('t.node_id')
350
+ .where('n.unique_id', '=', stored)
351
+ .where('t.workspace_id', '=', workspace.id)
352
+ .execute()
353
+ : await db.q
354
+ .selectFrom('data_type as t')
355
+ .innerJoin('node as n', 'n.id', 't.node_id')
356
+ .select('t.node_id')
357
+ .where('n.unique_id', '=', stored)
358
+ .where('t.workspace_id', '=', workspace.id)
359
+ .execute()
360
+ return rows.length > 0 ? stored : key
361
+ }
362
+ const own = (key: string) => this.#stored(key)
363
+ const properties: PropertyTypeModel[] = []
364
+ for (const p of aggregate.properties)
365
+ properties.push({
366
+ ...p,
367
+ key: own(p.key),
368
+ dataTypeKey: await copied('data_type', p.dataTypeKey),
369
+ containerKey: p.containerKey ? own(p.containerKey) : null,
370
+ })
371
+ const compositions = []
372
+ for (const c of aggregate.compositions)
373
+ compositions.push({ ...c, contentTypeKey: await copied('content_type', c.contentTypeKey) })
374
+ const allowedContentTypes = []
375
+ for (const c of aggregate.allowedContentTypes)
376
+ allowedContentTypes.push({
377
+ ...c,
378
+ contentTypeKey: await copied('content_type', c.contentTypeKey),
379
+ })
380
+ return {
381
+ ...aggregate,
382
+ key: own(aggregate.key),
383
+ containers: aggregate.containers.map((c) => ({
384
+ ...c,
385
+ key: own(c.key),
386
+ parentKey: c.parentKey ? own(c.parentKey) : null,
387
+ })),
388
+ properties,
389
+ compositions,
390
+ allowedContentTypes,
391
+ }
392
+ }
393
+
394
+ /** Saves the workspace's copy of a type, marking each row with the key it stands for. */
395
+ async #saveCopy(
396
+ aggregate: ContentTypeAggregate,
397
+ options: SaveContentTypeOptions,
398
+ ): Promise<ContentTypeAggregate> {
399
+ return this.#db.transaction(async (tx) => {
400
+ const stored = await this.#asStored(tx, aggregate)
401
+ await this.#copies(tx).save(stored, options)
402
+ const node = await new NodeRepository(tx).byKey(stored.key)
403
+ if (!node) throw new Error(`The copy of "${aggregate.alias}" was not saved.`)
404
+ await tx.q
405
+ .updateTable('content_type')
406
+ .set({ origin_key: normaliseUuid(aggregate.key) })
407
+ .where('node_id', '=', node.id)
408
+ .execute()
409
+ for (const p of aggregate.properties)
410
+ await tx.q
411
+ .updateTable('property_type')
412
+ .set({ origin_key: normaliseUuid(p.key) })
413
+ .where('unique_id', '=', this.#stored(p.key))
414
+ .execute()
415
+ for (const c of aggregate.containers)
416
+ await tx.q
417
+ .updateTable('property_type_group')
418
+ .set({ origin_key: normaliseUuid(c.key) })
419
+ .where('unique_id', '=', this.#stored(c.key))
420
+ .execute()
421
+ return (await this.inWorkspace(this.#workspace)
422
+ .#within(tx)
423
+ .byKey(aggregate.key)) as ContentTypeAggregate
424
+ })
425
+ }
426
+
427
+ #within(db: Db): ContentTypeRepository {
428
+ return new ContentTypeRepository(db, {
429
+ nodeState: this.#nodeState,
430
+ kind: this.#kind,
431
+ ...(this.#workspace ? { workspace: this.#workspace } : {}),
432
+ ...(this.#copiesOf === undefined ? {} : { copiesOf: this.#copiesOf }),
433
+ })
135
434
  }
136
435
 
137
436
  /** The node object type this repository's types carry. */
@@ -157,6 +456,15 @@ export class ContentTypeRepository {
157
456
  }
158
457
 
159
458
  async byKey(key: string): Promise<ContentTypeAggregate | undefined> {
459
+ if (this.#workspace) {
460
+ const copy = await this.#copyOf(key)
461
+ if (copy?.retired) return undefined
462
+ if (copy) {
463
+ const stored = await this.#copies().byKey(this.#stored(key))
464
+ return stored ? this.#asRead(stored) : undefined
465
+ }
466
+ return this.#shared().byKey(key)
467
+ }
160
468
  const node = await this.#nodes.byKey(key)
161
469
  if (!node || node.objectType !== this.#objectType) return undefined
162
470
  return this.#load(node.id, node.key, node.text ?? '', node.parentId)
@@ -167,6 +475,21 @@ export class ContentTypeRepository {
167
475
  alias: string,
168
476
  options: { includeRetired?: boolean } = {},
169
477
  ): Promise<ContentTypeAggregate | undefined> {
478
+ if (this.#workspace) {
479
+ const found = (await this.#listed()).find((t) => t.alias === alias)
480
+ if (found) return this.byKey(found.key)
481
+ // A retired copy comes back by alias, as Shared's retired types do.
482
+ if (!options.includeRetired) return undefined
483
+ const retired = await this.#db.q
484
+ .selectFrom('content_type')
485
+ .select('origin_key')
486
+ .where('workspace_id', '=', this.#workspace.id)
487
+ .where('alias', '=', alias)
488
+ .execute()
489
+ if (!retired[0]) return undefined
490
+ const stored = await this.#copies().byKey(this.#stored(String(retired[0].origin_key)))
491
+ return stored ? this.#asRead(stored) : undefined
492
+ }
170
493
  const rows = await this.#db.q
171
494
  .selectFrom('content_type as ct')
172
495
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -179,11 +502,24 @@ export class ContentTypeRepository {
179
502
  }
180
503
 
181
504
  async aliasExists(alias: string, exceptKey?: string): Promise<boolean> {
505
+ if (this.#workspace) {
506
+ const except = exceptKey ? normaliseUuid(exceptKey) : undefined
507
+ const kinds: ContentTypeKind[] = ['document', 'media', 'member']
508
+ for (const kind of kinds) {
509
+ const listed = await new ContentTypeRepository(this.#db, {
510
+ kind,
511
+ workspace: this.#workspace,
512
+ }).#listed()
513
+ if (listed.some((t) => t.alias === alias && t.key !== except)) return true
514
+ }
515
+ return false
516
+ }
182
517
  const rows = await this.#db.q
183
518
  .selectFrom('content_type as ct')
184
519
  .innerJoin('node as n', 'n.id', 'ct.node_id')
185
520
  .select((eb) => eb.fn.countAll().as('n'))
186
521
  .where('ct.alias', '=', alias)
522
+ .where('ct.workspace_id', 'is', null)
187
523
  .$if(Boolean(exceptKey), (q) =>
188
524
  q.where('n.unique_id', '<>', normaliseUuid(exceptKey as string)),
189
525
  )
@@ -196,6 +532,7 @@ export class ContentTypeRepository {
196
532
  skip: number,
197
533
  take: number,
198
534
  ): Promise<{ total: number; items: ContentTypeAggregate[] }> {
535
+ if (this.#workspace) return this.#listedPage((t) => t.allowAtRoot, skip, take)
199
536
  const matching = this.#db.q
200
537
  .selectFrom('content_type as ct')
201
538
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -229,6 +566,7 @@ export class ContentTypeRepository {
229
566
  skip: number,
230
567
  take: number,
231
568
  ): Promise<{ total: number; items: ContentTypeAggregate[] }> {
569
+ if (this.#workspace) return this.#listedPage((t) => t.isElement && t.allowInLibrary, skip, take)
232
570
  const matching = this.#db.q
233
571
  .selectFrom('content_type as ct')
234
572
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -254,11 +592,47 @@ export class ContentTypeRepository {
254
592
  return { total: Number(totals[0]?.n ?? 0) - hidden, items }
255
593
  }
256
594
 
595
+ /** A page of the workspace's listed types that pass `keep`, loaded. */
596
+ async #listedPage(
597
+ keep: (t: ListedType) => boolean,
598
+ skip: number,
599
+ take: number,
600
+ ): Promise<{ total: number; items: ContentTypeAggregate[] }> {
601
+ const items: ContentTypeAggregate[] = []
602
+ for (const t of (await this.#listed()).filter(keep)) {
603
+ const aggregate = await this.byKey(t.key)
604
+ if (aggregate && !aggregate.pending) items.push(aggregate)
605
+ }
606
+ return { total: items.length, items: items.slice(skip, skip + take) }
607
+ }
608
+
257
609
  /**
258
610
  * Why an item of type `typeKey` may not sit under `parentKey` (null: the top
259
611
  * level), as its parent's type allows children; nothing when it may.
260
612
  */
261
613
  async placementRefusal(typeKey: string, parentKey: string | null): Promise<string | undefined> {
614
+ if (this.#workspace) {
615
+ const type = await this.byKey(typeKey)
616
+ if (!type) return undefined
617
+ if (parentKey === null)
618
+ return type.allowedAsRoot ? undefined : `"${type.name}" isn't allowed at the top level.`
619
+ const parents = await this.#db.q
620
+ .selectFrom('node as n')
621
+ .innerJoin('content as c', 'c.node_id', 'n.id')
622
+ .innerJoin('node as tn', 'tn.id', 'c.content_type_id')
623
+ .leftJoin('content_type as tct', 'tct.node_id', 'tn.id')
624
+ .select(['n.text', 'tn.unique_id', 'tct.origin_key'])
625
+ .where('n.unique_id', '=', normaliseUuid(parentKey))
626
+ .execute()
627
+ const parent = parents[0]
628
+ if (!parent) return undefined
629
+ const parentType = await this.byKey(String(parent.origin_key ?? parent.unique_id))
630
+ return parentType?.allowedContentTypes.some(
631
+ (c) => normaliseUuid(c.contentTypeKey) === normaliseUuid(typeKey),
632
+ )
633
+ ? undefined
634
+ : `"${type.name}" isn't allowed under "${parent.text ?? parentKey}".`
635
+ }
262
636
  const types = await this.#db.q
263
637
  .selectFrom('node as n')
264
638
  .innerJoin('content_type as ct', 'ct.node_id', 'n.id')
@@ -296,6 +670,14 @@ export class ContentTypeRepository {
296
670
  skip: number,
297
671
  take: number,
298
672
  ): Promise<{ total: number; items: ContentTypeAggregate[] }> {
673
+ if (this.#workspace) {
674
+ const items: ContentTypeAggregate[] = []
675
+ for (const child of (await this.byKey(key))?.allowedContentTypes ?? []) {
676
+ const aggregate = await this.byKey(child.contentTypeKey)
677
+ if (aggregate && !aggregate.pending) items.push(aggregate)
678
+ }
679
+ return { total: items.length, items: items.slice(skip, skip + take) }
680
+ }
299
681
  const node = await this.#nodes.byKey(key)
300
682
  if (!node) return { total: 0, items: [] }
301
683
  const rows = await this.#db.q
@@ -318,8 +700,9 @@ export class ContentTypeRepository {
318
700
  aggregate: ContentTypeAggregate,
319
701
  options: SaveContentTypeOptions = {},
320
702
  ): Promise<ContentTypeAggregate> {
703
+ if (this.#workspace) return this.#saveCopy(aggregate, options)
321
704
  return this.#db.transaction(async (tx) => {
322
- const repo = new ContentTypeRepository(tx, { nodeState: this.#nodeState, kind: this.#kind })
705
+ const repo = this.#within(tx)
323
706
  const bool = (value: boolean) => tx.dialect.boolValue(value)
324
707
  const now = DbDate.toDb(new Date())
325
708
  const existing = await repo.nodes.byKey(aggregate.key)
@@ -374,6 +757,7 @@ export class ContentTypeRepository {
374
757
  .values({
375
758
  node_id: nodeId,
376
759
  ...typeValues,
760
+ workspace_id: this.#copiesOf ?? null,
377
761
  thumbnail: 'folder.png',
378
762
  since_state_id: options.sinceStateId ?? null,
379
763
  })
@@ -494,14 +878,19 @@ export class ContentTypeRepository {
494
878
  validation_reg_exp: property.regEx ?? null,
495
879
  validation_reg_exp_message: property.regExMessage ?? null,
496
880
  label_on_top: bool(property.labelOnTop),
497
- variations: variationFlags(property.variesByCulture, property.variesBySegment),
881
+ variations:
882
+ variationFlags(property.variesByCulture, property.variesBySegment) |
883
+ (property.variesByEnvironment ? ENVIRONMENT_VARIATION : 0),
498
884
  since_version: property.sinceVersion ?? null,
499
885
  }
500
886
  const found = await tx.q
501
887
  .selectFrom('property_type')
502
- .select('id')
888
+ .select(['id', 'variations'])
503
889
  .where('unique_id', '=', key)
504
890
  .execute()
891
+ // Only a schema sync says whether it varies by environment; a backoffice save keeps it.
892
+ if (property.variesByEnvironment === undefined && found[0])
893
+ columns.variations |= Number(found[0].variations) & ENVIRONMENT_VARIATION
505
894
  if (found[0]) {
506
895
  const id = Number(found[0].id)
507
896
  await tx.q
@@ -509,6 +898,16 @@ export class ContentTypeRepository {
509
898
  .set({ ...columns, retired_at: null })
510
899
  .where('id', '=', id)
511
900
  .execute()
901
+ // Story 387: turned off, each environment's own value goes; the shared one stays.
902
+ if (
903
+ property.variesByEnvironment === false &&
904
+ (Number(found[0].variations) & ENVIRONMENT_VARIATION) !== 0
905
+ )
906
+ await tx.q
907
+ .deleteFrom('property_value')
908
+ .where('property_type_id', '=', id)
909
+ .where('environment', 'is not', null)
910
+ .execute()
512
911
  // Only a schema sync says; a backoffice save leaves it as it was.
513
912
  if (property.searchable !== undefined)
514
913
  await tx.q
@@ -676,6 +1075,8 @@ export class ContentTypeRepository {
676
1075
  .select(['p.id', 'p.alias', 'ct.alias as type_alias'])
677
1076
  .where('p.retired_at', 'is not', null)
678
1077
  .where('p.retired_at', '<', DbDate.toDb(olderThan))
1078
+ // A workspace's copies are its own, and go when it does (story 376).
1079
+ .where('ct.workspace_id', 'is', null)
679
1080
  .execute()
680
1081
  const purged: Array<{ type: string; alias: string }> = []
681
1082
  await this.#db.transaction(async (tx) => {
@@ -702,6 +1103,7 @@ export class ContentTypeRepository {
702
1103
 
703
1104
  /** Every live type, cheap enough while types number in the dozens. */
704
1105
  async all(): Promise<ContentTypeAggregate[]> {
1106
+ if (this.#workspace) return this.byKeys((await this.#listed()).map((t) => t.key))
705
1107
  const rows = await this.#db.q
706
1108
  .selectFrom('content_type as ct')
707
1109
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -733,6 +1135,7 @@ export class ContentTypeRepository {
733
1135
 
734
1136
  /** Every live type's alias by its key, without loading the types themselves. */
735
1137
  async aliasesByKey(): Promise<Map<string, string>> {
1138
+ if (this.#workspace) return new Map((await this.#listed()).map((t) => [t.key, t.alias]))
736
1139
  const rows = await this.#db.q
737
1140
  .selectFrom('content_type as ct')
738
1141
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -745,6 +1148,8 @@ export class ContentTypeRepository {
745
1148
 
746
1149
  /** The aliases of the types that are a site's settings (story 058). */
747
1150
  async siteSettingsAliases(): Promise<string[]> {
1151
+ if (this.#workspace)
1152
+ return (await this.#listed()).filter((t) => t.siteSettings).map((t) => t.alias)
748
1153
  const rows = await this.#db.q
749
1154
  .selectFrom('content_type as ct')
750
1155
  .innerJoin('node as n', 'n.id', 'ct.node_id')
@@ -900,6 +1305,28 @@ export class ContentTypeRepository {
900
1305
  }
901
1306
 
902
1307
  async delete(key: string): Promise<boolean> {
1308
+ if (this.#workspace) {
1309
+ const copy = await this.#copyOf(key)
1310
+ if (copy?.retired) return false
1311
+ const shared =
1312
+ (await this.#nodes.byKey(key))?.objectType === CONTENT_TYPE_OBJECT_TYPES[this.#kind].item
1313
+ // A Shared type removed in the workspace is a retired copy, which hides Shared's.
1314
+ if (shared) {
1315
+ if (!copy) {
1316
+ const type = await this.#shared().byKey(key)
1317
+ if (!type) return false
1318
+ await this.#saveCopy(type, {})
1319
+ }
1320
+ await this.#db.q
1321
+ .updateTable('content_type')
1322
+ .set({ retired_at: DbDate.toDb(new Date()) })
1323
+ .where('workspace_id', '=', this.#workspace.id)
1324
+ .where('origin_key', '=', normaliseUuid(key))
1325
+ .execute()
1326
+ return true
1327
+ }
1328
+ return copy ? this.#copies().delete(this.#stored(key)) : false
1329
+ }
903
1330
  const node = await this.#nodes.byKey(key)
904
1331
  if (!node || node.objectType !== this.#objectType) return false
905
1332
  return this.#db.transaction(async (tx) => {
@@ -1063,6 +1490,7 @@ export class ContentTypeRepository {
1063
1490
  sortOrder: Number(row.sort_order),
1064
1491
  variesByCulture: variesByCulture(Number(row.variations)),
1065
1492
  variesBySegment: variesBySegment(Number(row.variations)),
1493
+ ...(variesByEnvironment(Number(row.variations)) ? { variesByEnvironment: true } : {}),
1066
1494
  mandatory: fromDbBool(row.mandatory),
1067
1495
  mandatoryMessage: (row.mandatory_message as string | null) ?? null,
1068
1496
  regEx: (row.validation_reg_exp as string | null) ?? null,