@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.
@@ -23,6 +23,8 @@ export interface NodeRow {
23
23
  createDate: Date | undefined
24
24
  /** 0 for a media folder, which a tree lists before the files beside it (story 246); 1 otherwise. */
25
25
  treeGroup: number
26
+ /** The workspace a page made in one belongs to (story 375); null for Shared's. */
27
+ workspaceId?: number | null
26
28
  }
27
29
 
28
30
  export function mapNode(row: Record<string, unknown>): NodeRow {
@@ -38,6 +40,8 @@ export function mapNode(row: Record<string, unknown>): NodeRow {
38
40
  objectType: row.node_object_type ? normaliseUuid(String(row.node_object_type)) : null,
39
41
  createDate: DbDate.fromDb(row.create_date),
40
42
  treeGroup: row.tree_group === undefined || row.tree_group === null ? 1 : Number(row.tree_group),
43
+ workspaceId:
44
+ row.workspace_id === undefined || row.workspace_id === null ? null : Number(row.workspace_id),
41
45
  }
42
46
  }
43
47
 
@@ -53,6 +57,7 @@ const NODE_COLUMNS = [
53
57
  'node_object_type',
54
58
  'create_date',
55
59
  'tree_group',
60
+ 'workspace_id',
56
61
  ] as const
57
62
 
58
63
  export interface CreateNodeInit {
@@ -64,6 +69,16 @@ export interface CreateNodeInit {
64
69
  sortOrder?: number
65
70
  /** 0 for a media folder (story 246); 1, the default, for everything else. */
66
71
  treeGroup?: number
72
+ /** A page made in a workspace (story 375). */
73
+ workspaceId?: number
74
+ }
75
+
76
+ /** What an item of each kind made in a workspace is. */
77
+ const WORKSPACE_OBJECT_TYPES: Record<string, string> = {
78
+ [ObjectTypes.Document]: ObjectTypes.WorkspaceDocument,
79
+ [ObjectTypes.Media]: ObjectTypes.WorkspaceMedia,
80
+ [ObjectTypes.Element]: ObjectTypes.WorkspaceElement,
81
+ [ObjectTypes.DocumentBlueprint]: ObjectTypes.WorkspaceDocumentBlueprint,
67
82
  }
68
83
 
69
84
  export class NodeRepository {
@@ -126,6 +141,7 @@ export class NodeRepository {
126
141
  node_object_type: init.objectType,
127
142
  create_date: now,
128
143
  tree_group: init.treeGroup ?? 1,
144
+ workspace_id: init.workspaceId ?? null,
129
145
  })
130
146
  .execute()
131
147
  const created = await this.byKey(key)
@@ -156,11 +172,24 @@ export class NodeRepository {
156
172
  take: number,
157
173
  trashed = false,
158
174
  excludeKeys: readonly string[] = [],
175
+ /** With a workspace, its own pages are children too (story 375). */
176
+ workspaceId?: number,
159
177
  ): Promise<Page<NodeRow>> {
160
178
  const matching = this.#db.q
161
179
  .selectFrom('node')
162
180
  .where('parent_id', '=', parentId)
163
- .where('node_object_type', '=', objectType)
181
+ .where((eb) =>
182
+ workspaceId === undefined
183
+ ? eb('node_object_type', '=', objectType)
184
+ : eb.or([
185
+ eb('node_object_type', '=', objectType),
186
+ eb.and([
187
+ // The workspace's own of this kind (stories 375, 390).
188
+ eb('node_object_type', '=', WORKSPACE_OBJECT_TYPES[objectType] ?? objectType),
189
+ eb('workspace_id', '=', workspaceId),
190
+ ]),
191
+ ]),
192
+ )
164
193
  .where('trashed', '=', this.#db.dialect.boolValue(trashed))
165
194
  .$if(excludeKeys.length > 0, (q) =>
166
195
  q.where('unique_id', 'not in', excludeKeys.map(normaliseUuid)),
@@ -185,13 +214,29 @@ export class NodeRepository {
185
214
  objectTypes: readonly string[],
186
215
  skip: number,
187
216
  take: number,
217
+ /** Story 392: a workspace's own are children too, and those it deleted are not. */
218
+ workspace?: { id: number; hidden: readonly string[] },
188
219
  ): Promise<Page<NodeRow>> {
189
220
  if (objectTypes.length === 0) return { total: 0, items: [] }
221
+ const own = objectTypes.flatMap((t) => {
222
+ const mapped = WORKSPACE_OBJECT_TYPES[t]
223
+ return mapped ? [mapped] : []
224
+ })
190
225
  const matching = this.#db.q
191
226
  .selectFrom('node')
192
227
  .where('parent_id', '=', parentId)
193
- .where('node_object_type', 'in', objectTypes)
228
+ .where((eb) =>
229
+ workspace && own.length > 0
230
+ ? eb.or([
231
+ eb('node_object_type', 'in', objectTypes),
232
+ eb.and([eb('node_object_type', 'in', own), eb('workspace_id', '=', workspace.id)]),
233
+ ])
234
+ : eb('node_object_type', 'in', objectTypes),
235
+ )
194
236
  .where('trashed', '=', this.#db.dialect.boolValue(false))
237
+ .$if((workspace?.hidden.length ?? 0) > 0, (q) =>
238
+ q.where('unique_id', 'not in', (workspace?.hidden ?? []).map(normaliseUuid)),
239
+ )
195
240
  const totals = await matching.select((eb) => eb.fn.countAll().as('n')).execute()
196
241
  const rows = await matching
197
242
  .select(NODE_COLUMNS)
@@ -56,6 +56,9 @@ export interface TransferChange {
56
56
  eventId: number | null
57
57
  }
58
58
 
59
+ /** A run as the content commands list it: a bundle, a whole site, or a bundle's revert. */
60
+ const BUNDLE_KINDS = ['bundle', 'replace']
61
+
59
62
  export class TransferRunRepository {
60
63
  #db: Db
61
64
  constructor(db: Db) {
@@ -166,10 +169,12 @@ export class TransferRunRepository {
166
169
  }
167
170
 
168
171
  /** Runs, newest first. */
172
+ /** The bundles applied here and their reverts: not merges, edits or reverted changes (stories 381, 388). */
169
173
  async recent(limit = 20, offset = 0): Promise<TransferRun[]> {
170
174
  const rows = await this.#db.q
171
175
  .selectFrom('content_transfer_run')
172
176
  .selectAll()
177
+ .where('change_kind', 'in', BUNDLE_KINDS)
173
178
  .orderBy('started_at', 'desc')
174
179
  .orderBy('id', 'desc')
175
180
  .limit(limit)
@@ -182,6 +187,7 @@ export class TransferRunRepository {
182
187
  const row = await this.#db.q
183
188
  .selectFrom('content_transfer_run')
184
189
  .select(sql<number>`count(*)`.as('n'))
190
+ .where('change_kind', 'in', BUNDLE_KINDS)
185
191
  .executeTakeFirst()
186
192
  return Number(row?.n ?? 0)
187
193
  }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * A workspace's files (story 376): texts kept once each by the SHA-256 of their
3
+ * text (`file_blob`), and each workspace's list of path and hash
4
+ * (`workspace_file`). The list is taken when the workspace opens; the hash then
5
+ * is each file's merge base, and the workspace changes only its own list.
6
+ */
7
+ import { createHash } from 'node:crypto'
8
+ import type { Db } from '../database.ts'
9
+
10
+ /** The hash a file is kept by: the SHA-256 of its text, in hex. */
11
+ export const fileHash = (text: string): string => createHash('sha256').update(text).digest('hex')
12
+
13
+ /** One file the workspace changed: what it was at open, and is now (null: not there). */
14
+ export interface WorkspaceFileChange {
15
+ path: string
16
+ base: string | null
17
+ now: string | null
18
+ class: string | null
19
+ }
20
+
21
+ export class WorkspaceFileRepository {
22
+ #db: Db
23
+
24
+ constructor(db: Db) {
25
+ this.#db = db
26
+ }
27
+
28
+ async #put(text: string): Promise<string> {
29
+ const hash = fileHash(text)
30
+ const found = await this.#db.q
31
+ .selectFrom('file_blob')
32
+ .select('hash')
33
+ .where('hash', '=', hash)
34
+ .execute()
35
+ if (found.length === 0)
36
+ await this.#db.q
37
+ .insertInto('file_blob')
38
+ .values({ hash, text, size: Buffer.byteLength(text) })
39
+ .execute()
40
+ return hash
41
+ }
42
+
43
+ async #texts(hashes: readonly string[]): Promise<Map<string, string>> {
44
+ const wanted = [...new Set(hashes)]
45
+ const out = new Map<string, string>()
46
+ for (let n = 0; n < wanted.length; n += 500)
47
+ for (const row of await this.#db.q
48
+ .selectFrom('file_blob')
49
+ .select(['hash', 'text'])
50
+ .where('hash', 'in', wanted.slice(n, n + 500))
51
+ .execute())
52
+ out.set(String(row.hash), String(row.text))
53
+ return out
54
+ }
55
+
56
+ /** The workspace's list as Shared's files are at open: each file's base and its own. */
57
+ async snapshot(workspaceId: number, files: ReadonlyMap<string, string>): Promise<void> {
58
+ for (const [path, text] of files) {
59
+ const hash = await this.#put(text)
60
+ await this.#db.q
61
+ .insertInto('workspace_file')
62
+ .values({ workspace_id: workspaceId, path, base_hash: hash, hash, class: null })
63
+ .execute()
64
+ }
65
+ }
66
+
67
+ /** The workspace's files now, by path; `prefix` keeps one folder's. */
68
+ async files(workspaceId: number, prefix = ''): Promise<Map<string, string>> {
69
+ const rows = await this.#db.q
70
+ .selectFrom('workspace_file')
71
+ .select(['path', 'hash'])
72
+ .where('workspace_id', '=', workspaceId)
73
+ .where('hash', 'is not', null)
74
+ .execute()
75
+ const kept = rows.filter((row) => String(row.path).startsWith(prefix))
76
+ const texts = await this.#texts(kept.map((row) => String(row.hash)))
77
+ return new Map(kept.map((row) => [String(row.path), texts.get(String(row.hash)) ?? '']))
78
+ }
79
+
80
+ /** Each file whose text is not what it was at open. */
81
+ async changes(workspaceId: number, prefix = ''): Promise<WorkspaceFileChange[]> {
82
+ const rows = (
83
+ await this.#db.q
84
+ .selectFrom('workspace_file')
85
+ .select(['path', 'base_hash', 'hash', 'class'])
86
+ .where('workspace_id', '=', workspaceId)
87
+ .orderBy('path')
88
+ .execute()
89
+ ).filter(
90
+ (row) =>
91
+ (row.base_hash ?? null) !== (row.hash ?? null) && String(row.path).startsWith(prefix),
92
+ )
93
+ const texts = await this.#texts(
94
+ rows.flatMap((row) => [row.base_hash, row.hash].filter((h): h is string => Boolean(h))),
95
+ )
96
+ return rows.map((row) => ({
97
+ path: String(row.path),
98
+ base: row.base_hash ? (texts.get(String(row.base_hash)) ?? null) : null,
99
+ now: row.hash ? (texts.get(String(row.hash)) ?? null) : null,
100
+ class: (row.class as string | null) ?? null,
101
+ }))
102
+ }
103
+
104
+ /** Writes a file in the workspace, or removes it (null), with the class of the change. */
105
+ async write(
106
+ workspaceId: number,
107
+ path: string,
108
+ text: string | null,
109
+ changeClass: string | null = null,
110
+ ): Promise<void> {
111
+ const hash = text === null ? null : await this.#put(text)
112
+ const found = await this.#db.q
113
+ .selectFrom('workspace_file')
114
+ .select('path')
115
+ .where('workspace_id', '=', workspaceId)
116
+ .where('path', '=', path)
117
+ .execute()
118
+ if (found.length > 0)
119
+ await this.#db.q
120
+ .updateTable('workspace_file')
121
+ .set({ hash, class: changeClass })
122
+ .where('workspace_id', '=', workspaceId)
123
+ .where('path', '=', path)
124
+ .execute()
125
+ else if (hash !== null)
126
+ await this.#db.q
127
+ .insertInto('workspace_file')
128
+ .values({ workspace_id: workspaceId, path, base_hash: null, hash, class: changeClass })
129
+ .execute()
130
+ }
131
+
132
+ /** A file brought up to Shared's (story 380's "update from Shared"): a new base, and its text. */
133
+ async rebase(
134
+ workspaceId: number,
135
+ path: string,
136
+ base: string | null,
137
+ text: string | null,
138
+ ): Promise<void> {
139
+ const baseHash = base === null ? null : await this.#put(base)
140
+ const hash = text === null ? null : await this.#put(text)
141
+ await this.#db.q
142
+ .deleteFrom('workspace_file')
143
+ .where('workspace_id', '=', workspaceId)
144
+ .where('path', '=', path)
145
+ .execute()
146
+ if (baseHash !== null || hash !== null)
147
+ await this.#db.q
148
+ .insertInto('workspace_file')
149
+ .values({
150
+ workspace_id: workspaceId,
151
+ path,
152
+ base_hash: baseHash,
153
+ hash,
154
+ class: baseHash === hash ? null : 'none',
155
+ })
156
+ .execute()
157
+ }
158
+
159
+ /** Whether an open workspace has changed the file at `path` (story 376). */
160
+ async changedInOpenWorkspace(path: string): Promise<boolean> {
161
+ const rows = await this.#db.q
162
+ .selectFrom('workspace_file as f')
163
+ .innerJoin('workspace as w', 'w.id', 'f.workspace_id')
164
+ .select(['f.base_hash', 'f.hash'])
165
+ .where('f.path', '=', path)
166
+ .where('w.state', '=', 'open')
167
+ .execute()
168
+ return rows.some((row) => (row.base_hash ?? null) !== (row.hash ?? null))
169
+ }
170
+
171
+ /** Removes the workspace's list, then every text no list or change still keeps. */
172
+ async discard(workspaceId: number): Promise<void> {
173
+ await this.#db.q.deleteFrom('workspace_file').where('workspace_id', '=', workspaceId).execute()
174
+ await this.collect()
175
+ }
176
+
177
+ /** Removes every kept text no workspace's list names. */
178
+ async collect(): Promise<void> {
179
+ await this.#db.q
180
+ .deleteFrom('file_blob')
181
+ .where((eb) =>
182
+ eb.and([
183
+ eb(
184
+ 'hash',
185
+ 'not in',
186
+ eb.selectFrom('workspace_file').select('hash').where('hash', 'is not', null),
187
+ ),
188
+ eb(
189
+ 'hash',
190
+ 'not in',
191
+ eb.selectFrom('workspace_file').select('base_hash').where('base_hash', 'is not', null),
192
+ ),
193
+ // A change's texts are its history (story 381).
194
+ eb(
195
+ 'hash',
196
+ 'not in',
197
+ eb.selectFrom('change_item').select('before_hash').where('before_hash', 'is not', null),
198
+ ),
199
+ eb(
200
+ 'hash',
201
+ 'not in',
202
+ eb.selectFrom('change_item').select('after_hash').where('after_hash', 'is not', null),
203
+ ),
204
+ ]),
205
+ )
206
+ .execute()
207
+ }
208
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Links to a workspace's site (story 379): each kept by the SHA-256 of its
3
+ * secret, with who made it, when it lapses, and whether it was withdrawn.
4
+ */
5
+ import { normaliseUuid } from '@crombolo/core'
6
+ import type { Db } from '../database.ts'
7
+ import { DbDate } from '../dialect.ts'
8
+
9
+ export interface WorkspaceLink {
10
+ id: number
11
+ workspaceId: number
12
+ madeBy: string
13
+ createdAt: Date
14
+ expiresAt: Date
15
+ withdrawnAt: Date | null
16
+ }
17
+
18
+ export class WorkspaceLinkRepository {
19
+ #db: Db
20
+
21
+ constructor(db: Db) {
22
+ this.#db = db
23
+ }
24
+
25
+ #view(row: Record<string, unknown>): WorkspaceLink {
26
+ return {
27
+ id: Number(row.id),
28
+ workspaceId: Number(row.workspace_id),
29
+ madeBy: normaliseUuid(String(row.made_by)),
30
+ createdAt: DbDate.fromDb(row.created_at) ?? new Date(0),
31
+ expiresAt: DbDate.fromDb(row.expires_at) ?? new Date(0),
32
+ withdrawnAt: DbDate.fromDb(row.withdrawn_at) ?? null,
33
+ }
34
+ }
35
+
36
+ async make(link: {
37
+ workspaceId: number
38
+ madeBy: string
39
+ secretHash: string
40
+ expiresAt: Date
41
+ }): Promise<WorkspaceLink> {
42
+ await this.#db.q
43
+ .insertInto('workspace_link')
44
+ .values({
45
+ workspace_id: link.workspaceId,
46
+ secret_hash: link.secretHash,
47
+ made_by: normaliseUuid(link.madeBy),
48
+ created_at: DbDate.toDb(new Date()),
49
+ expires_at: DbDate.toDb(link.expiresAt),
50
+ withdrawn_at: null,
51
+ })
52
+ .execute()
53
+ return (await this.bySecretHash(link.secretHash)) as WorkspaceLink
54
+ }
55
+
56
+ async bySecretHash(hash: string): Promise<WorkspaceLink | undefined> {
57
+ const rows = await this.#db.q
58
+ .selectFrom('workspace_link')
59
+ .selectAll()
60
+ .where('secret_hash', '=', hash)
61
+ .execute()
62
+ return rows[0] ? this.#view(rows[0]) : undefined
63
+ }
64
+
65
+ async byId(id: number): Promise<WorkspaceLink | undefined> {
66
+ const rows = await this.#db.q
67
+ .selectFrom('workspace_link')
68
+ .selectAll()
69
+ .where('id', '=', id)
70
+ .execute()
71
+ return rows[0] ? this.#view(rows[0]) : undefined
72
+ }
73
+
74
+ /** A workspace's links, newest first. */
75
+ async of(workspaceId: number): Promise<WorkspaceLink[]> {
76
+ return (
77
+ await this.#db.q
78
+ .selectFrom('workspace_link')
79
+ .selectAll()
80
+ .where('workspace_id', '=', workspaceId)
81
+ .orderBy('id', 'desc')
82
+ .execute()
83
+ ).map((row) => this.#view(row))
84
+ }
85
+
86
+ async withdraw(workspaceId: number, id: number): Promise<boolean> {
87
+ // Read first: not every driver reports the rows an update changed.
88
+ const link = await this.byId(id)
89
+ if (!link || link.workspaceId !== workspaceId || link.withdrawnAt) return false
90
+ await this.#db.q
91
+ .updateTable('workspace_link')
92
+ .set({ withdrawn_at: DbDate.toDb(new Date()) })
93
+ .where('id', '=', id)
94
+ .execute()
95
+ return true
96
+ }
97
+ }