@crombolo/server 0.69.0 → 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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/workspace-dictionary.ts +287 -0
  10. package/src/adapters/workspace-file-port.ts +160 -0
  11. package/src/adapters/workspace-languages.ts +94 -0
  12. package/src/approvals-api.ts +16 -7
  13. package/src/bundle-api.ts +19 -16
  14. package/src/bundle-install.ts +4 -0
  15. package/src/change-transfer.ts +676 -0
  16. package/src/changes-api.ts +258 -0
  17. package/src/component-templates-api.ts +2 -2
  18. package/src/config.ts +162 -22
  19. package/src/content-events.ts +65 -1
  20. package/src/content-operations.ts +22 -3
  21. package/src/core.ts +2 -0
  22. package/src/environment-values-api.ts +161 -0
  23. package/src/host-token.ts +30 -1
  24. package/src/node-operations.ts +150 -2
  25. package/src/ports.ts +174 -52
  26. package/src/remote-changes.ts +279 -0
  27. package/src/remote-schema.ts +126 -0
  28. package/src/remote-workspaces.ts +82 -0
  29. package/src/remote.ts +289 -192
  30. package/src/schema-transfer.ts +240 -41
  31. package/src/schema.ts +7 -2
  32. package/src/seed/compile.ts +13 -1
  33. package/src/seed/values.ts +3 -0
  34. package/src/server.ts +971 -364
  35. package/src/settings.ts +123 -5
  36. package/src/site-sections.ts +1 -1
  37. package/src/workspace-access.ts +152 -0
  38. package/src/workspace-checks.ts +299 -0
  39. package/src/workspace-losses.ts +95 -0
  40. package/src/workspace-processes.ts +306 -0
  41. package/src/workspace-render-child.ts +168 -0
  42. package/src/workspace-schema-dir.ts +100 -0
  43. package/src/workspace-schema.ts +598 -0
  44. package/src/workspace-sites.ts +179 -0
  45. package/src/workspace-views.ts +121 -0
  46. package/src/workspaces.ts +1031 -0
@@ -35,7 +35,13 @@ const COLLECTION_SORTS: Record<string, MediaSortField> = {
35
35
  /** The Media section's reads; its writes go through the media operations (story 165). */
36
36
  export function createMediaPort(
37
37
  db: Db,
38
- options: { nodeState?: NodeSchemaState; nodeId?: string; valueIntake?: ValueIntake } = {},
38
+ options: {
39
+ nodeState?: NodeSchemaState
40
+ nodeId?: string
41
+ valueIntake?: ValueIntake
42
+ /** A workspace's media (story 390). */
43
+ workspace?: number
44
+ } = {},
39
45
  ): MediaPort {
40
46
  const repo = new DocumentRepository(db, { ...options, kind: 'media' })
41
47
  const tree = async (rows: readonly NodeRow[]) => repo.treeItems(rows)
@@ -9,7 +9,13 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
9
9
  import { join, relative } from 'node:path'
10
10
  import type { PortFailure } from '@crombolo/api-management/domain'
11
11
  import type { ContentTypeAggregate, DataTypeModel, FormTypes } from '@crombolo/core'
12
- import { currentSchemaState, type Db, updateSchemaStateHash } from '@crombolo/data'
12
+ import {
13
+ currentSchemaState,
14
+ type Db,
15
+ updateSchemaStateHash,
16
+ WorkspaceFileRepository,
17
+ type WorkspaceScope,
18
+ } from '@crombolo/data'
13
19
  import {
14
20
  type ChangeClass,
15
21
  exportSchemaSet,
@@ -229,6 +235,88 @@ export function createSchemaFileWriter(
229
235
  }
230
236
  }
231
237
 
238
+ /** Where a workspace keeps its copy of `schema/` among its files (story 376). */
239
+ export const WORKSPACE_SCHEMA_PREFIX = 'schema/'
240
+
241
+ /** What is wrong with a workspace's definitions, as its own rows would write them. */
242
+ export async function workspaceSchemaProblems(
243
+ db: Db,
244
+ files: SchemaFiles,
245
+ workspace: WorkspaceScope,
246
+ ): Promise<string[]> {
247
+ const set = await exportSchemaSet(db, '1.0.0', { workspace })
248
+ return validateSchemaSet(set, {
249
+ componentAliases: files.componentAliases(),
250
+ types: files.formTypes,
251
+ }).map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
252
+ }
253
+
254
+ /**
255
+ * The writer for a workspace (story 376): a type or data type saved there is
256
+ * written into the workspace's own copy of `schema/`, with the class of the
257
+ * change. The version, languages and URL options are the site's and are left;
258
+ * a site whose files are read-only refuses the save, as Shared's does.
259
+ */
260
+ export function createWorkspaceSchemaFileWriter(
261
+ db: Db,
262
+ files: SchemaFiles,
263
+ kind: SchemaTypeKind,
264
+ workspace: WorkspaceScope,
265
+ ): SchemaFileWriter {
266
+ const shared = createSchemaFileWriter(db, files, kind)
267
+ const store = new WorkspaceFileRepository(db)
268
+ const pathFor = (dir: string, alias: string) =>
269
+ `${WORKSPACE_SCHEMA_PREFIX}${dir}/${fileNameFor(alias)}`
270
+ const typePath = (alias: string) => pathFor(TYPE_KIND_FILES[kind].dir, alias)
271
+ let changeClass: ChangeClass = 'none'
272
+ const exported = () => exportSchemaSet(db, '1.0.0', { workspace })
273
+ return {
274
+ refuse: (aggregate) => shared.refuse(aggregate),
275
+ async bumpVersion(classification) {
276
+ changeClass = classification
277
+ },
278
+ async write(aggregate, previousAlias) {
279
+ const set = await exported()
280
+ const list =
281
+ kind === 'document'
282
+ ? set.contentTypes
283
+ : kind === 'media'
284
+ ? (set.mediaTypes ?? [])
285
+ : (set.memberTypes ?? [])
286
+ const type = list.find((t) => t.key === aggregate.key)
287
+ if (!type) return
288
+ if (previousAlias && previousAlias !== aggregate.alias)
289
+ await store.write(workspace.id, typePath(previousAlias), null, changeClass)
290
+ await store.write(
291
+ workspace.id,
292
+ typePath(aggregate.alias),
293
+ writeContentType(type, kind),
294
+ changeClass,
295
+ )
296
+ changeClass = 'none'
297
+ },
298
+ async remove(alias) {
299
+ await store.write(workspace.id, typePath(alias), null, 'breaking')
300
+ },
301
+ async writeDataType(model) {
302
+ if (!model.alias) return
303
+ const dataType = (await exported()).dataTypes.find((d) => d.key === model.key)
304
+ await store.write(
305
+ workspace.id,
306
+ pathFor('data-types', model.alias),
307
+ dataType ? writeDataType(dataType) : null,
308
+ 'additive',
309
+ )
310
+ },
311
+ async removeDataType(alias) {
312
+ await store.write(workspace.id, pathFor('data-types', alias), null, 'breaking')
313
+ },
314
+ async writeLanguages() {},
315
+ async writeUrlOptions() {},
316
+ async rewriteAll() {},
317
+ }
318
+ }
319
+
232
320
  /** Where the backoffice writes schema files, and whether it may. */
233
321
  export function schemaFiles(config: CromboloConfig): SchemaFiles {
234
322
  const store = config.schemaStore
@@ -0,0 +1,287 @@
1
+ /**
2
+ * The dictionary a workspace holds (story 392): a file in its copy,
3
+ * `content/dictionary.jsonl`, one item per line with its key, parent and translations,
4
+ * in name order, so a merge goes three ways by line and an item both sides changed is a
5
+ * conflict. Read and written here as the dictionary port, as the back office asks of it
6
+ * in a workspace; until it is first changed there, it is Shared's. docs/workspaces.md.
7
+ */
8
+
9
+ import type {
10
+ DictionaryItemModel,
11
+ DictionaryPort,
12
+ DictionaryWriteStatus,
13
+ } from '@crombolo/api-management/domain'
14
+ import { normaliseUuid } from '@crombolo/core'
15
+ import { type Db, DictionaryRepository, WorkspaceFileRepository } from '@crombolo/data'
16
+
17
+ /** Where a workspace keeps its dictionary among its files. */
18
+ export const WORKSPACE_DICTIONARY = 'content/dictionary.jsonl'
19
+
20
+ /** The dictionary as the file holds it: a line per item, by name. Pure. */
21
+ export function writeDictionaryLines(items: readonly DictionaryItemModel[]): string {
22
+ return [...items]
23
+ .sort((a, b) => a.name.localeCompare(b.name))
24
+ .map((item) =>
25
+ JSON.stringify({
26
+ key: normaliseUuid(item.key),
27
+ name: item.name,
28
+ parentKey: item.parentKey ? normaliseUuid(item.parentKey) : null,
29
+ translations: [...item.translations].sort((a, b) => a.isoCode.localeCompare(b.isoCode)),
30
+ }),
31
+ )
32
+ .map((line) => `${line}\n`)
33
+ .join('')
34
+ }
35
+
36
+ /** The items a file holds; a line that is not one is left out. Pure. */
37
+ export function readDictionaryLines(text: string): DictionaryItemModel[] {
38
+ const out: DictionaryItemModel[] = []
39
+ for (const line of text.split('\n')) {
40
+ if (!line.trim()) continue
41
+ try {
42
+ const item = JSON.parse(line) as DictionaryItemModel
43
+ if (item.key && item.name) out.push(item)
44
+ } catch {}
45
+ }
46
+ return out
47
+ }
48
+
49
+ /** Shared's dictionary, as a workspace's file holds it. */
50
+ export async function sharedDictionaryLines(db: Db): Promise<string> {
51
+ const items = await new DictionaryRepository(db).all()
52
+ return writeDictionaryLines(
53
+ items.map((i) => ({
54
+ key: i.key,
55
+ name: i.name,
56
+ parentKey: i.parentKey ?? null,
57
+ translations: i.translations.map((t) => ({ isoCode: t.isoCode, translation: t.translation })),
58
+ })),
59
+ )
60
+ }
61
+
62
+ /** The dictionary port, in a workspace: its file, read and written. */
63
+ export function workspaceDictionaryPort(db: Db, workspaceId: number): DictionaryPort {
64
+ const store = new WorkspaceFileRepository(db)
65
+ const load = async () => {
66
+ const text = (await store.files(workspaceId, WORKSPACE_DICTIONARY)).get(WORKSPACE_DICTIONARY)
67
+ return readDictionaryLines(text ?? (await sharedDictionaryLines(db)))
68
+ }
69
+ const save = async (items: DictionaryItemModel[]) => {
70
+ const known = (await store.files(workspaceId, WORKSPACE_DICTIONARY)).has(WORKSPACE_DICTIONARY)
71
+ const text = writeDictionaryLines(items)
72
+ if (known) await store.write(workspaceId, WORKSPACE_DICTIONARY, text)
73
+ else
74
+ await store.rebase(workspaceId, WORKSPACE_DICTIONARY, await sharedDictionaryLines(db), text)
75
+ }
76
+ const same = (a: string | null, b: string | null) =>
77
+ (a ? normaliseUuid(a) : null) === (b ? normaliseUuid(b) : null)
78
+ const descendants = (items: DictionaryItemModel[], key: string): Set<string> => {
79
+ const out = new Set<string>([normaliseUuid(key)])
80
+ let grew = true
81
+ while (grew) {
82
+ grew = false
83
+ for (const i of items)
84
+ if (i.parentKey && out.has(normaliseUuid(i.parentKey)) && !out.has(normaliseUuid(i.key))) {
85
+ out.add(normaliseUuid(i.key))
86
+ grew = true
87
+ }
88
+ }
89
+ return out
90
+ }
91
+ return {
92
+ async all(filter) {
93
+ const items = await load()
94
+ return filter
95
+ ? items.filter((i) => i.name.toLowerCase().includes(filter.toLowerCase()))
96
+ : items
97
+ },
98
+ async get(key) {
99
+ return (await load()).find((i) => same(i.key, key))
100
+ },
101
+ async items(keys) {
102
+ const items = await load()
103
+ return items.filter((i) => keys.some((k) => same(i.key, k)))
104
+ },
105
+ async children(parentKey) {
106
+ const items = await load()
107
+ return items
108
+ .filter((i) => same(i.parentKey, parentKey))
109
+ .map((i) => ({
110
+ key: i.key,
111
+ name: i.name,
112
+ parentKey: i.parentKey,
113
+ hasChildren: items.some((c) => same(c.parentKey, i.key)),
114
+ }))
115
+ },
116
+ async ancestry(key) {
117
+ const items = await load()
118
+ const chain: DictionaryItemModel[] = []
119
+ let at = items.find((i) => same(i.key, key))
120
+ while (at) {
121
+ chain.unshift(at)
122
+ const parent: string | null = at.parentKey
123
+ at = parent ? items.find((i) => same(i.key, parent)) : undefined
124
+ }
125
+ return chain
126
+ },
127
+ async create(item): Promise<DictionaryWriteStatus> {
128
+ const items = await load()
129
+ if (items.some((i) => same(i.key, item.key))) return 'DuplicateItemKey'
130
+ if (items.some((i) => i.name.toLowerCase() === item.name.toLowerCase())) return 'DuplicateKey'
131
+ if (item.parentKey && !items.some((i) => same(i.key, item.parentKey))) return 'ParentNotFound'
132
+ await save([...items, item])
133
+ return 'Success'
134
+ },
135
+ async update(key, change): Promise<DictionaryWriteStatus> {
136
+ const items = await load()
137
+ const at = items.findIndex((i) => same(i.key, key))
138
+ if (at < 0) return 'NotFound'
139
+ if (items.some((i, n) => n !== at && i.name.toLowerCase() === change.name.toLowerCase()))
140
+ return 'DuplicateKey'
141
+ items[at] = { ...(items[at] as DictionaryItemModel), ...change }
142
+ await save(items)
143
+ return 'Success'
144
+ },
145
+ async move(key, parentKey): Promise<DictionaryWriteStatus> {
146
+ const items = await load()
147
+ const at = items.findIndex((i) => same(i.key, key))
148
+ if (at < 0) return 'NotFound'
149
+ if (parentKey && descendants(items, key).has(normaliseUuid(parentKey))) return 'InvalidParent'
150
+ items[at] = { ...(items[at] as DictionaryItemModel), parentKey }
151
+ await save(items)
152
+ return 'Success'
153
+ },
154
+ async delete(key): Promise<DictionaryWriteStatus> {
155
+ const items = await load()
156
+ if (!items.some((i) => same(i.key, key))) return 'NotFound'
157
+ const gone = descendants(items, key)
158
+ await save(items.filter((i) => !gone.has(normaliseUuid(i.key))))
159
+ return 'Success'
160
+ },
161
+ async export() {
162
+ return undefined
163
+ },
164
+ async import() {
165
+ return {
166
+ ok: false,
167
+ status: 'Invalid',
168
+ reason: 'A dictionary file is imported in Shared, for now.',
169
+ }
170
+ },
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Makes Shared's dictionary the merged one (story 392), on the merge's transaction:
176
+ * new items under their parents first, then each changed, moved, and those gone,
177
+ * children before their parents.
178
+ */
179
+ export async function applyDictionaryLines(tx: Db, text: string): Promise<void> {
180
+ const repo = new DictionaryRepository(tx)
181
+ const wanted = readDictionaryLines(text)
182
+ const now = await repo.all()
183
+ const byKey = new Map(now.map((i) => [normaliseUuid(i.key), i]))
184
+ const depth = (item: DictionaryItemModel): number => {
185
+ let n = 0
186
+ let at = item.parentKey
187
+ while (at && n < 64) {
188
+ n++
189
+ at =
190
+ wanted.find((w) => normaliseUuid(w.key) === normaliseUuid(at as string))?.parentKey ?? null
191
+ }
192
+ return n
193
+ }
194
+ for (const item of [...wanted].sort((a, b) => depth(a) - depth(b))) {
195
+ const here = byKey.get(normaliseUuid(item.key))
196
+ if (!here) {
197
+ await repo.create({ ...item, translations: [...item.translations] })
198
+ continue
199
+ }
200
+ if (
201
+ here.name !== item.name ||
202
+ JSON.stringify([...here.translations].sort((a, b) => a.isoCode.localeCompare(b.isoCode))) !==
203
+ JSON.stringify(item.translations)
204
+ )
205
+ await repo.update(here.key, { name: item.name, translations: item.translations })
206
+ if ((here.parentKey ?? null) !== (item.parentKey ?? null))
207
+ await repo.move(here.key, item.parentKey)
208
+ }
209
+ const keep = new Set(wanted.map((w) => normaliseUuid(w.key)))
210
+ const gone = now.filter((i) => !keep.has(normaliseUuid(i.key)))
211
+ for (const item of gone.reverse()) await repo.delete(item.key).catch(() => 'NotFound')
212
+ }
213
+
214
+ /** The dictionary a workspace's site renders with (story 392): its own, else Shared's. */
215
+ export async function workspaceDictionary(db: Db, workspaceId: number) {
216
+ const text = (await new WorkspaceFileRepository(db).files(workspaceId, WORKSPACE_DICTIONARY)).get(
217
+ WORKSPACE_DICTIONARY,
218
+ )
219
+ if (text === undefined) return undefined
220
+ const items = readDictionaryLines(text)
221
+ const byKey = new Map(items.map((i) => [normaliseUuid(i.key), i]))
222
+ const translations = new Map<string, Map<string, string>>()
223
+ for (const item of items)
224
+ translations.set(item.name, new Map(item.translations.map((t) => [t.isoCode, t.translation])))
225
+ const outline = items.map((i) => ({
226
+ key: normaliseUuid(i.key),
227
+ name: i.name,
228
+ parentName: i.parentKey ? (byKey.get(normaliseUuid(i.parentKey))?.name ?? null) : null,
229
+ }))
230
+ return { translations, outline }
231
+ }
232
+
233
+ /**
234
+ * Shared's dictionary port, each write by someone recorded as their change (story 392):
235
+ * the dictionary as the file holds it, before and after.
236
+ */
237
+ export function recordingDictionaryPort(
238
+ db: Db,
239
+ port: DictionaryPort,
240
+ record: (by: string, before: string, after: string) => Promise<void>,
241
+ ): DictionaryPort {
242
+ const recorded = async (by: string | undefined, write: () => Promise<DictionaryWriteStatus>) => {
243
+ const before = by ? await sharedDictionaryLines(db) : ''
244
+ const status = await write()
245
+ if (status === 'Success' && by) {
246
+ const after = await sharedDictionaryLines(db)
247
+ if (after !== before) await record(by, before, after)
248
+ }
249
+ return status
250
+ }
251
+ return {
252
+ ...port,
253
+ create: (item, by) => recorded(by, () => port.create(item)),
254
+ update: (key, change, by) => recorded(by, () => port.update(key, change)),
255
+ move: (key, parentKey, by) => recorded(by, () => port.move(key, parentKey)),
256
+ delete: (key, by) => recorded(by, () => port.delete(key)),
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Three ways by item key (story 392): each item as one side changed it, and null where
262
+ * both changed the same item differently. Pure.
263
+ */
264
+ export function mergeDictionaryLines(
265
+ base: string | null,
266
+ mine: string | null,
267
+ theirs: string | null,
268
+ ): { text: string } | null {
269
+ const byKey = (text: string | null) =>
270
+ new Map(readDictionaryLines(text ?? '').map((i) => [normaliseUuid(i.key), JSON.stringify(i)]))
271
+ const b = byKey(base)
272
+ const m = byKey(mine)
273
+ const t = byKey(theirs)
274
+ const out: DictionaryItemModel[] = []
275
+ for (const key of new Set([...b.keys(), ...m.keys(), ...t.keys()])) {
276
+ const was = b.get(key)
277
+ const ours = m.get(key)
278
+ const other = t.get(key)
279
+ let kept: string | undefined
280
+ if (ours === other) kept = ours
281
+ else if (ours === was) kept = other
282
+ else if (other === was) kept = ours
283
+ else return null
284
+ if (kept) out.push(JSON.parse(kept) as DictionaryItemModel)
285
+ }
286
+ return { text: writeDictionaryLines(out) }
287
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * A workspace's components, stylesheets or scripts (story 377), as the Management
3
+ * API sees them with the `Crombolo-Workspace` header: the workspace's own copy,
4
+ * taken from Shared's files as it opened, read and written in its file list.
5
+ * Folders are the paths' own; making or removing one is done in Shared.
6
+ */
7
+ import type { FileEntry, FileResult, FileSystemPort } from '@crombolo/api-management/domain'
8
+ import { type Db, WorkspaceFileRepository } from '@crombolo/data'
9
+
10
+ /** The most a workspace keeps of one file. */
11
+ export const WORKSPACE_FILE_LIMIT = 1024 * 1024
12
+
13
+ export interface WorkspaceFileAreaOptions {
14
+ /** Where the area's files sit in the workspace's list: `components/`, `stylesheets/`, `scripts/`. */
15
+ prefix: string
16
+ extension: string
17
+ also?: readonly string[]
18
+ rewrites?: readonly string[]
19
+ /** A component must compile before it is kept. */
20
+ compiles?: boolean
21
+ /** The site keeps these files read-only (story 337): a workspace may not change them either. */
22
+ readOnly?: boolean
23
+ }
24
+
25
+ const INVALID = /[<>:"|?*\\/]/
26
+
27
+ /** Why a component's source does not compile, or undefined when it does. */
28
+ export function compileProblem(source: string): string | undefined {
29
+ try {
30
+ new Bun.Transpiler({ loader: 'tsx' }).transformSync(source)
31
+ return undefined
32
+ } catch (error) {
33
+ const at = (error as { position?: { line?: number; lineText?: string } }).position
34
+ const where = at?.line ? ` on line ${at.line}` : ''
35
+ const text = at?.lineText?.trim()
36
+ return `${(error as Error).message.trim()}${where}${text ? `: ${text}` : ''}`
37
+ }
38
+ }
39
+
40
+ export function createWorkspaceFilePort(
41
+ db: Db,
42
+ workspaceId: number,
43
+ options: WorkspaceFileAreaOptions,
44
+ ): FileSystemPort {
45
+ const store = new WorkspaceFileRepository(db)
46
+ const accepted = [options.extension, ...(options.also ?? [])].map((e) => e.toLowerCase())
47
+ const keyOf = (path: string) => `${options.prefix}${path.replace(/^\/+/, '')}`
48
+ const toPath = (key: string) => `/${key.slice(options.prefix.length)}`
49
+ const files = async () => {
50
+ const all = await store.files(workspaceId, options.prefix)
51
+ return new Map([...all].filter(([key]) => accepted.some((e) => key.toLowerCase().endsWith(e))))
52
+ }
53
+ const folderOf = (path: string) => {
54
+ const parts = path.split('/').filter(Boolean)
55
+ return parts.length > 1 ? `/${parts.slice(0, -1).join('/')}` : null
56
+ }
57
+ const nameOf = (name: string): string | 'InvalidName' | 'InvalidFileExtension' => {
58
+ const trimmed = name.trim()
59
+ if (!trimmed || trimmed.startsWith('.') || INVALID.test(trimmed)) return 'InvalidName'
60
+ const lower = trimmed.toLowerCase()
61
+ if (accepted.some((e) => lower.endsWith(e))) return trimmed
62
+ const rewrite = options.rewrites?.find((r) => lower.endsWith(r.toLowerCase()))
63
+ if (rewrite) return `${trimmed.slice(0, -rewrite.length)}${options.extension}`
64
+ return 'InvalidFileExtension'
65
+ }
66
+ const refusedRead: FileResult = { ok: false, status: 'ReadOnly' }
67
+ const checked = (content: string): FileResult | undefined => {
68
+ if (Buffer.byteLength(content) > WORKSPACE_FILE_LIMIT)
69
+ return { ok: false, status: 'TooLarge', detail: 'A file of up to a megabyte is kept.' }
70
+ const problem = options.compiles ? compileProblem(content) : undefined
71
+ return problem ? { ok: false, status: 'DoesNotCompile', detail: problem } : undefined
72
+ }
73
+ const entriesUnder = async (parentPath: string | null): Promise<FileEntry[]> => {
74
+ const parent = parentPath ? parentPath.replace(/\/+$/, '') : ''
75
+ const out = new Map<string, FileEntry>()
76
+ for (const key of (await files()).keys()) {
77
+ const path = toPath(key)
78
+ if (parent && !path.startsWith(`${parent}/`)) continue
79
+ const rest = path.slice(parent.length + 1).split('/')
80
+ const name = rest[0] as string
81
+ const own = `${parent}/${name}`
82
+ const isFolder = rest.length > 1
83
+ if (!out.has(own))
84
+ out.set(own, {
85
+ path: own,
86
+ name,
87
+ parentPath: parent || null,
88
+ isFolder,
89
+ hasChildren: isFolder,
90
+ })
91
+ }
92
+ return [...out.values()].sort(
93
+ (a, b) =>
94
+ Number(b.isFolder) - Number(a.isFolder) ||
95
+ a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
96
+ )
97
+ }
98
+ return {
99
+ async children(parentPath) {
100
+ return entriesUnder(parentPath)
101
+ },
102
+ async entry(path) {
103
+ const parent = folderOf(path)
104
+ return (await entriesUnder(parent)).find((e) => e.path === `/${path.replace(/^\/+/, '')}`)
105
+ },
106
+ async read(path) {
107
+ const content = (await files()).get(keyOf(path))
108
+ if (content === undefined) return undefined
109
+ const at = `/${path.replace(/^\/+/, '')}`
110
+ return { path: at, name: at.split('/').pop() as string, parentPath: folderOf(at), content }
111
+ },
112
+ async create(parentPath, name, content) {
113
+ if (options.readOnly) return refusedRead
114
+ const stored = nameOf(name)
115
+ if (stored === 'InvalidName' || stored === 'InvalidFileExtension')
116
+ return { ok: false, status: stored }
117
+ const path = `${parentPath ? parentPath.replace(/\/+$/, '') : ''}/${stored}`
118
+ if ((await files()).has(keyOf(path))) return { ok: false, status: 'AlreadyExists' }
119
+ const refused = checked(content)
120
+ if (refused) return refused
121
+ await store.write(workspaceId, keyOf(path), content, 'additive')
122
+ return { ok: true, path }
123
+ },
124
+ async update(path, content) {
125
+ if (options.readOnly) return refusedRead
126
+ if (!(await files()).has(keyOf(path))) return { ok: false, status: 'NotFound' }
127
+ const refused = checked(content)
128
+ if (refused) return refused
129
+ await store.write(workspaceId, keyOf(path), content, 'none')
130
+ return { ok: true, path: `/${path.replace(/^\/+/, '')}` }
131
+ },
132
+ async rename(path, name) {
133
+ if (options.readOnly) return refusedRead
134
+ const all = await files()
135
+ const content = all.get(keyOf(path))
136
+ if (content === undefined) return { ok: false, status: 'NotFound' }
137
+ const stored = nameOf(name)
138
+ if (stored === 'InvalidName' || stored === 'InvalidFileExtension')
139
+ return { ok: false, status: stored }
140
+ const target = `${folderOf(`/${path.replace(/^\/+/, '')}`) ?? ''}/${stored}`
141
+ if (target !== `/${path.replace(/^\/+/, '')}` && all.has(keyOf(target)))
142
+ return { ok: false, status: 'AlreadyExists' }
143
+ await store.write(workspaceId, keyOf(target), content, 'breaking')
144
+ await store.write(workspaceId, keyOf(path), null, 'breaking')
145
+ return { ok: true, path: target }
146
+ },
147
+ async delete(path) {
148
+ if (options.readOnly) return refusedRead
149
+ if (!(await files()).has(keyOf(path))) return { ok: false, status: 'NotFound' }
150
+ await store.write(workspaceId, keyOf(path), null, 'breaking')
151
+ return { ok: true, path: `/${path.replace(/^\/+/, '')}` }
152
+ },
153
+ async createFolder() {
154
+ return { ok: false, status: 'ReadOnly' }
155
+ },
156
+ async deleteFolder() {
157
+ return { ok: false, status: 'ReadOnly' }
158
+ },
159
+ }
160
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The languages a workspace holds (story 392): its copy of `schema/languages.toml`,
3
+ * read and written as the localization port in that workspace. The merge brings the
4
+ * file into Shared with the other definitions. docs/workspaces.md.
5
+ */
6
+ import type { LanguageInput, LocalizationPort } from '@crombolo/api-management/domain'
7
+ import { type Db, WorkspaceFileRepository } from '@crombolo/data'
8
+ import { parseLanguages, type SchemaLanguage, writeLanguages } from '@crombolo/schema'
9
+ import { WORKSPACE_SCHEMA_PREFIX } from './schema-files.ts'
10
+
11
+ /** Where a workspace keeps its languages among its files. */
12
+ export const WORKSPACE_LANGUAGES = `${WORKSPACE_SCHEMA_PREFIX}languages.toml`
13
+
14
+ const toInput = (l: SchemaLanguage): LanguageInput => ({
15
+ isoCode: l.iso,
16
+ name: l.name,
17
+ isDefault: l.default,
18
+ isMandatory: l.mandatory,
19
+ fallbackIsoCode: l.fallback ?? null,
20
+ })
21
+
22
+ const toSchema = (l: LanguageInput): SchemaLanguage => ({
23
+ iso: l.isoCode,
24
+ name: l.name,
25
+ default: l.isDefault,
26
+ mandatory: l.isMandatory,
27
+ ...(l.fallbackIsoCode ? { fallback: l.fallbackIsoCode } : {}),
28
+ })
29
+
30
+ /** The languages as `schema/languages.toml` holds them. */
31
+ export const writeLanguagesFile = (languages: readonly LanguageInput[]): string =>
32
+ writeLanguages(languages.map(toSchema))
33
+
34
+ const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase()
35
+
36
+ /** The localization port, in a workspace: its languages file, else Shared's languages. */
37
+ export function workspaceLocalizationPort(
38
+ db: Db,
39
+ shared: LocalizationPort,
40
+ workspaceId: number,
41
+ ): LocalizationPort {
42
+ const store = new WorkspaceFileRepository(db)
43
+ const own = async () =>
44
+ (await store.files(workspaceId, WORKSPACE_LANGUAGES)).get(WORKSPACE_LANGUAGES)
45
+ const load = async (): Promise<LanguageInput[]> => {
46
+ const text = await own()
47
+ const parsed = text === undefined ? undefined : parseLanguages('languages.toml', text).value
48
+ return parsed ? parsed.map(toInput) : shared.allLanguages()
49
+ }
50
+ const save = async (languages: LanguageInput[]) => {
51
+ const text = writeLanguages(languages.map(toSchema))
52
+ // The workspace took every file Shared had as it opened: without one, Shared had none.
53
+ if ((await own()) !== undefined) await store.write(workspaceId, WORKSPACE_LANGUAGES, text)
54
+ else await store.rebase(workspaceId, WORKSPACE_LANGUAGES, null, text)
55
+ }
56
+ return {
57
+ cultures: () => shared.cultures(),
58
+ allLanguages: load,
59
+ async language(isoCode) {
60
+ return (await load()).find((l) => same(l.isoCode, isoCode))
61
+ },
62
+ async saveLanguage(language) {
63
+ const languages = await load()
64
+ const rest = languages
65
+ .filter((l) => !same(l.isoCode, language.isoCode))
66
+ .map((l) => (language.isDefault ? { ...l, isDefault: false } : l))
67
+ const at = languages.findIndex((l) => same(l.isoCode, language.isoCode))
68
+ const next = [...rest]
69
+ next.splice(at < 0 ? next.length : at, 0, language)
70
+ await save(next)
71
+ },
72
+ async deleteLanguage(isoCode) {
73
+ const languages = await load()
74
+ const found = languages.find((l) => same(l.isoCode, isoCode))
75
+ if (!found) return 'not-found'
76
+ if (found.isDefault) return 'default'
77
+ if (languages.some((l) => l.fallbackIsoCode && same(l.fallbackIsoCode, isoCode)))
78
+ return 'in-use'
79
+ await save(languages.filter((l) => l !== found))
80
+ return 'deleted'
81
+ },
82
+ }
83
+ }
84
+
85
+ /** The languages a workspace holds, where its file reads; undefined where it has none. */
86
+ export async function workspaceLanguages(
87
+ db: Db,
88
+ workspaceId: number,
89
+ ): Promise<LanguageInput[] | undefined> {
90
+ const text = (await new WorkspaceFileRepository(db).files(workspaceId, WORKSPACE_LANGUAGES)).get(
91
+ WORKSPACE_LANGUAGES,
92
+ )
93
+ return text === undefined ? undefined : parseLanguages('languages.toml', text).value?.map(toInput)
94
+ }