rimecms 1.1.2 → 1.1.4

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 (73) hide show
  1. package/dist/adapter-sqlite/relations.server.d.ts +4 -4
  2. package/dist/core/adapter.d.ts +4 -4
  3. package/dist/core/fields/types.d.ts +34 -3
  4. package/dist/core/fields/types.test-d.d.ts +1 -0
  5. package/dist/core/fields/types.test-d.js +37 -0
  6. package/dist/core/i18n/en/fields.d.ts +1 -1
  7. package/dist/core/i18n/en/fields.js +1 -1
  8. package/dist/core/i18n/fr/fields.d.ts +1 -1
  9. package/dist/core/i18n/fr/fields.js +1 -1
  10. package/dist/core/pipeline/hooks/set-default-values.server.d.ts +1 -1
  11. package/dist/core/pipeline/hooks/set-default-values.server.js +25 -30
  12. package/dist/core/pipeline/persist/relations/diff.server.d.ts +4 -4
  13. package/dist/core/pipeline/persist/relations/extract.server.js +27 -45
  14. package/dist/core/prototype/area/api.server.d.ts +7 -1
  15. package/dist/core/prototype/area/api.server.js +3 -0
  16. package/dist/core/prototype/area/operations/update.d.ts +2 -1
  17. package/dist/core/prototype/collection/api.server.d.ts +16 -3
  18. package/dist/core/prototype/collection/api.server.js +6 -0
  19. package/dist/core/prototype/collection/operations/create.d.ts +2 -1
  20. package/dist/core/prototype/collection/operations/delete.js +6 -4
  21. package/dist/core/prototype/collection/operations/duplicate.js +2 -4
  22. package/dist/core/prototype/collection/operations/update-by-id.d.ts +2 -1
  23. package/dist/core/prototype/collection/thumbnail/hooks/set-document-thumbnail.server.js +9 -15
  24. package/dist/core/prototype/collection/upload/disk/delete.server.js +1 -1
  25. package/dist/core/prototype/shared/title/hooks/set-document-title.server.js +2 -2
  26. package/dist/core/prototype/shared/versions/hooks/handle-new-version.server.js +17 -1
  27. package/dist/fields/blocks/component/focus/BlocksFocus.svelte +21 -4
  28. package/dist/fields/blocks/component/focus/Inspector.svelte +12 -28
  29. package/dist/fields/blocks/component/focus/LayersList.svelte +4 -1
  30. package/dist/fields/blocks/component/focus/Renders.svelte +44 -28
  31. package/dist/fields/blocks/component/focus/Renders.svelte.d.ts +3 -0
  32. package/dist/fields/blocks/component/focus/StageAdd.svelte +42 -0
  33. package/dist/fields/blocks/component/focus/StageAdd.svelte.d.ts +6 -0
  34. package/dist/fields/blocks/component/focus/focus.svelte.d.ts +7 -13
  35. package/dist/fields/blocks/component/focus/focus.svelte.js +38 -33
  36. package/dist/fields/blocks/index.d.ts +26 -5
  37. package/dist/fields/blocks/index.js +8 -2
  38. package/dist/fields/relation/component/Relation.svelte +16 -3
  39. package/dist/fields/relation/component/Relation.svelte.d.ts +2 -1
  40. package/dist/fields/relation/component/RelationInline.svelte +6 -9
  41. package/dist/fields/relation/fetch.d.ts +12 -0
  42. package/dist/fields/relation/fetch.js +27 -0
  43. package/dist/fields/relation/index.d.ts +16 -7
  44. package/dist/fields/relation/index.js +20 -4
  45. package/dist/fields/relation/module.server.js +15 -18
  46. package/dist/fields/relation/populate.js +4 -21
  47. package/dist/fields/relation/relation.d.ts +38 -0
  48. package/dist/fields/relation/relation.js +55 -0
  49. package/dist/fields/relation/relation.test-d.d.ts +1 -0
  50. package/dist/fields/relation/relation.test-d.js +10 -0
  51. package/dist/fields/relation/value.d.ts +2 -2
  52. package/dist/fields/rich-text/component/Cell.svelte +2 -2
  53. package/dist/fields/rich-text/json.d.ts +4 -9
  54. package/dist/fields/rich-text/json.js +8 -6
  55. package/dist/fields/types.d.ts +4 -1
  56. package/dist/live/Consumer.svelte +3 -3
  57. package/dist/live/Consumer.svelte.d.ts +2 -2
  58. package/dist/panel/components/sections/collection/grid/grid-item/GridItem.svelte +7 -1
  59. package/dist/panel/components/ui/button/button.svelte +2 -3
  60. package/dist/panel/context/documentForm.svelte.js +2 -2
  61. package/dist/panel/style/index.css +4 -3
  62. package/dist/panel/style/palette.css +3 -3
  63. package/dist/panel/style/scheme.css +1 -0
  64. package/dist/public.d.ts +3 -3
  65. package/dist/public.js +3 -3
  66. package/dist/types.d.ts +1 -1
  67. package/dist/util/types.d.ts +1 -1
  68. package/dist/util/types.js +1 -1
  69. package/package.json +1 -1
  70. package/dist/fields/blocks/component/focus/StagePlaceholder.svelte +0 -86
  71. package/dist/fields/blocks/component/focus/StagePlaceholder.svelte.d.ts +0 -8
  72. package/dist/fields/relation/util.d.ts +0 -57
  73. package/dist/fields/relation/util.js +0 -86
@@ -1,5 +1,5 @@
1
1
  import type { AdapterDeps } from './types.server.js';
2
- import type { BeforeOperationRelation, Relation } from '../fields/relation/index.js';
2
+ import type { BeforeOperationRelation, RelationRow } from '../fields/relation/index.js';
3
3
  import type { PrototypeSlug } from '../core/prototype/types.js';
4
4
  declare const createRelationsHandle: ({ db, tables }: AdapterDeps) => {
5
5
  create: Create;
@@ -17,11 +17,11 @@ type DeleteFromPaths = (args: {
17
17
  }) => Promise<boolean>;
18
18
  type Delete = (args: {
19
19
  parentSlug: PrototypeSlug;
20
- relations: Relation[];
20
+ relations: RelationRow[];
21
21
  }) => Promise<boolean>;
22
22
  type Update = (args: {
23
23
  parentSlug: PrototypeSlug;
24
- relations: Relation[];
24
+ relations: RelationRow[];
25
25
  }) => Promise<boolean>;
26
26
  type Create = (args: {
27
27
  parentSlug: PrototypeSlug;
@@ -32,4 +32,4 @@ type GetAllRelations = (args: {
32
32
  parentSlug: PrototypeSlug;
33
33
  ownerId: string;
34
34
  locale?: string;
35
- }) => Promise<Relation[]>;
35
+ }) => Promise<RelationRow[]>;
@@ -1,7 +1,7 @@
1
1
  import type { BuiltArea, BuiltCollection } from './config/types.js';
2
2
  import type { OperationQuery } from './pipeline/types.js';
3
3
  import type { GenericBlock, PrototypeSlug, RawDoc, TreeBlock } from './prototype/types.js';
4
- import type { BeforeOperationRelation, Relation } from '../fields/relation/index.js';
4
+ import type { BeforeOperationRelation, RelationRow } from '../fields/relation/index.js';
5
5
  import type { Dic, WithOptional, WithRequired } from '../util/types.js';
6
6
  /**
7
7
  * What core requires of a database adapter.
@@ -273,11 +273,11 @@ export interface RelationsHandle {
273
273
  }): Promise<boolean>;
274
274
  update(args: {
275
275
  parentSlug: PrototypeSlug;
276
- relations: Relation[];
276
+ relations: RelationRow[];
277
277
  }): Promise<boolean>;
278
278
  delete(args: {
279
279
  parentSlug: PrototypeSlug;
280
- relations: Relation[];
280
+ relations: RelationRow[];
281
281
  }): Promise<boolean>;
282
282
  deleteFromPaths(args: {
283
283
  parentSlug: PrototypeSlug;
@@ -289,7 +289,7 @@ export interface RelationsHandle {
289
289
  parentSlug: PrototypeSlug;
290
290
  ownerId: string;
291
291
  locale?: string;
292
- }): Promise<Relation[]>;
292
+ }): Promise<RelationRow[]>;
293
293
  }
294
294
  /**
295
295
  * A page's address in one locale, as a collection with `$url` stores it.
@@ -1,4 +1,4 @@
1
- import type { RelationValue } from '../../fields/types.js';
1
+ import type { RelationInput, RelationRef, RelationValue } from '../../fields/types.js';
2
2
  /**
3
3
  * Type utilities that know about fields.
4
4
  *
@@ -6,8 +6,39 @@ import type { RelationValue } from '../../fields/types.js';
6
6
  * builder — so by the placement rule they belong with the concept, not with the generic
7
7
  * helpers.
8
8
  */
9
- export type WithRelationPopulated<T> = {
10
- [K in keyof T]: Required<T>[K] extends string ? T[K] : Required<T>[K] extends number ? T[K] : Required<T>[K] extends boolean ? T[K] : Required<T>[K] extends null ? T[K] : T[K] extends undefined ? undefined : NonNullable<T[K]> extends RelationValue<infer U> ? T[K] extends undefined ? undefined : U[] : T[K] extends Array<infer E> ? Array<WithRelationPopulated<E>> : T[K] extends object ? WithRelationPopulated<T[K]> : T[K];
9
+ /** The depths a read resolves, each mapped to the one its related documents are read at. */
10
+ type LessDepth = {
11
+ 1: 0;
12
+ 2: 1;
13
+ 3: 2;
14
+ 4: 3;
15
+ };
16
+ /**
17
+ * A document as a read at `depth` hands it back: each relation holds the related documents, read
18
+ * themselves at one depth less. Depth 0, past 4, or a depth the type cannot know (a `number`) is
19
+ * the document as typed, its relations refs or documents.
20
+ *
21
+ * ```ts
22
+ * WithRelationResolved<PagesDoc, 1>['hero']['thumbnail'] // MediasDoc[]
23
+ * WithRelationResolved<PagesDoc, 1>['sections'][0]['image'] // MediasDoc[], in a block too
24
+ * WithRelationResolved<PagesDoc, 1>['author'][0]['avatar'] // RelationValue<MediasDoc>
25
+ * ```
26
+ */
27
+ export type WithRelationResolved<T, D extends number = 1> = D extends keyof LessDepth ? Resolved<T, D> : T;
28
+ type Resolved<T, D extends keyof LessDepth> = {
29
+ [K in keyof T]: Required<T>[K] extends string | number | boolean | null ? T[K] : T[K] extends undefined ? undefined : T[K] extends Date | ((...args: any[]) => unknown) ? T[K] : IsRelation<NonNullable<T[K]>> extends true ? NonNullable<T[K]> extends RelationValue<infer U> ? WithRelationResolved<U, LessDepth[D]>[] : T[K] : T[K] extends Array<infer E> ? Array<Resolved<E, D>> : T[K] extends object ? Resolved<T[K], D> : T[K];
30
+ };
31
+ /** A relation's type is the only one with refs among its shapes. */
32
+ type IsRelation<V> = [Extract<V, RelationRef[]>] extends [never] ? false : true;
33
+ /**
34
+ * A document as a write takes it: each relation also takes bare ids, in a block or a group too.
35
+ *
36
+ * ```ts
37
+ * WithRelationInput<PagesDoc>['author'] // UsersDoc[] | RelationRef[] | string[] | string
38
+ * ```
39
+ */
40
+ export type WithRelationInput<T> = {
41
+ [K in keyof T]: Required<T>[K] extends string | number | boolean | null ? T[K] : T[K] extends Date | ((...args: any[]) => unknown) ? T[K] : IsRelation<NonNullable<T[K]>> extends true ? NonNullable<T[K]> extends RelationValue<infer U> ? RelationInput<U> : T[K] : T[K] extends Array<infer E> ? Array<WithRelationInput<E>> : T[K] extends object ? WithRelationInput<T[K]> : T[K];
11
42
  };
12
43
  /**
13
44
  * Re-exported from where it is defined: WithoutBuilders and FieldBuilder are mutually
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import { describe, expectTypeOf, it } from 'vitest';
2
+ describe('WithRelationResolved', () => {
3
+ it('resolves the relations at depth 1, and reads the related documents at depth 0', () => {
4
+ expectTypeOf().toEqualTypeOf();
5
+ expectTypeOf().toEqualTypeOf();
6
+ expectTypeOf().toEqualTypeOf();
7
+ });
8
+ it('walks blocks at the same depth', () => {
9
+ expectTypeOf().toEqualTypeOf();
10
+ expectTypeOf().toEqualTypeOf();
11
+ });
12
+ it('resolves the related documents too at depth 2', () => {
13
+ expectTypeOf().toEqualTypeOf();
14
+ });
15
+ it('keeps the other fields as they are', () => {
16
+ expectTypeOf().toEqualTypeOf();
17
+ expectTypeOf().toEqualTypeOf();
18
+ expectTypeOf().toEqualTypeOf();
19
+ });
20
+ it('is the document as typed at depth 0, and at a depth it cannot know', () => {
21
+ expectTypeOf().toEqualTypeOf();
22
+ expectTypeOf().toEqualTypeOf();
23
+ });
24
+ });
25
+ describe('WithRelationInput', () => {
26
+ it('lets a relation take bare ids, in a block too', () => {
27
+ expectTypeOf().toEqualTypeOf();
28
+ expectTypeOf().toEqualTypeOf();
29
+ expectTypeOf().toExtend();
30
+ expectTypeOf().toExtend();
31
+ });
32
+ it('keeps the other fields as they are', () => {
33
+ expectTypeOf().toEqualTypeOf();
34
+ expectTypeOf().toEqualTypeOf();
35
+ expectTypeOf().toEqualTypeOf();
36
+ });
37
+ });
@@ -70,7 +70,7 @@ declare namespace _default {
70
70
  let delete_item: string;
71
71
  let inside: string;
72
72
  let nothing_inside: string;
73
- let type_to_add_block: string;
73
+ let add_block_or_type: string;
74
74
  let slug_hint: string;
75
75
  let build_from: string;
76
76
  let choose: string;
@@ -70,7 +70,7 @@ export default {
70
70
  delete_item: 'Delete item',
71
71
  inside: 'Inside $1',
72
72
  nothing_inside: 'Nothing inside yet: drop an item here, or add one.',
73
- type_to_add_block: 'Type $1 to add a block',
73
+ add_block_or_type: 'Add a block or type $1',
74
74
  slug_hint: 'Lowercase letters, digits and dashes.',
75
75
  build_from: 'Build it from the $1',
76
76
  choose: 'Choose…',
@@ -70,7 +70,7 @@ declare namespace _default {
70
70
  let delete_item: string;
71
71
  let inside: string;
72
72
  let nothing_inside: string;
73
- let type_to_add_block: string;
73
+ let add_block_or_type: string;
74
74
  let slug_hint: string;
75
75
  let build_from: string;
76
76
  let choose: string;
@@ -70,7 +70,7 @@ export default {
70
70
  delete_item: 'Supprimer l’élément',
71
71
  inside: 'Dans $1',
72
72
  nothing_inside: 'Rien dedans pour l’instant : déposez un élément ici, ou ajoutez-en un.',
73
- type_to_add_block: 'Tapez $1 pour ajouter un bloc',
73
+ add_block_or_type: 'Ajouter un bloc ou tapez $1',
74
74
  slug_hint: 'Lettres minuscules, chiffres et tirets.',
75
75
  build_from: 'Le générer depuis le champ $1',
76
76
  choose: 'Choisir…',
@@ -23,6 +23,6 @@ type GetDefaultValue = (args: {
23
23
  config: FormFieldBuilder;
24
24
  adapter: Adapter;
25
25
  }) => Promise<any>;
26
- /** A relation's default is ids; they become junction rows, checked against the collection. */
26
+ /** A relation's default becomes junction rows, checked against the collection. */
27
27
  export declare const getDefaultValue: GetDefaultValue;
28
28
  export {};
@@ -64,39 +64,34 @@ const isEmpty = (config, key, value) => {
64
64
  }
65
65
  };
66
66
  /**
67
- * This function convert any default value string | string[] of ids
68
- * to a RelationValue from an existing relation record
67
+ * A relation's default, as junction rows: the refs `use.defaultValue` answers, kept in their
68
+ * order, those that name no document left out.
69
69
  */
70
70
  const defaultRelationValue = async (config, key, adapter) => {
71
- const buildRelation = async (defaultValue) => {
72
- // A default relation is one id or a list of them. Anything else names no document, and must
73
- // not fall through to a `where(undefined)` that would hand back every row in the collection.
74
- const ids = typeof defaultValue === 'string'
75
- ? [defaultValue]
76
- : Array.isArray(defaultValue)
77
- ? defaultValue
78
- : [];
79
- // `existingIds` on the adapter, written out: which of these ids name a document that exists.
80
- // The ordinary read, projected — see collection/nested/hooks/add-children.server.ts.
81
- //
82
- // `relationTo` is typed `CollectionSlug` by `RelationFieldBuilder.to`, so a relation names a
83
- // collection by construction.
84
- const existing = ids.length
85
- ? await adapter
86
- .collection(config.get.relationTo)
87
- .findMany({ query: { where: { id: { in_array: ids } } }, select: ['id'] })
88
- : [];
89
- return existing.map(({ id: documentId }, index) => ({
90
- id: null,
91
- relationTo: config.get.relationTo,
92
- path: key,
93
- position: index,
94
- documentId
95
- }));
96
- };
97
- return await buildRelation(config.use.defaultValue({ event: getRequestEvent() }));
71
+ const refs = config.use.defaultValue({ event: getRequestEvent() });
72
+ const ids = refs.map((ref) => ref.documentId);
73
+ // `existingIds` on the adapter, written out: which of these ids name a document that exists.
74
+ // The ordinary read, projected — see collection/nested/hooks/add-children.server.ts.
75
+ //
76
+ // `relationTo` is typed `CollectionSlug` by `RelationFieldBuilder.to`, so a relation names a
77
+ // collection by construction.
78
+ const existing = ids.length
79
+ ? await adapter
80
+ .collection(config.get.relationTo)
81
+ .findMany({ query: { where: { id: { in_array: ids } } }, select: ['id'] })
82
+ : [];
83
+ const found = new Set(existing.map(({ id }) => id));
84
+ return ids
85
+ .filter((id) => found.has(id))
86
+ .map((documentId, position) => ({
87
+ id: null,
88
+ relationTo: config.get.relationTo,
89
+ path: key,
90
+ position,
91
+ documentId
92
+ }));
98
93
  };
99
- /** A relation's default is ids; they become junction rows, checked against the collection. */
94
+ /** A relation's default becomes junction rows, checked against the collection. */
100
95
  export const getDefaultValue = async ({ key, config, adapter }) => {
101
96
  if (config instanceof RelationFieldBuilder) {
102
97
  return await defaultRelationValue(config, key, adapter);
@@ -1,12 +1,12 @@
1
1
  import type { BeforeOperationRelation } from '../../../../fields/relation/index.js';
2
- import type { Relation } from '../../../../fields/relation/index.js';
2
+ import type { RelationRow } from '../../../../fields/relation/index.js';
3
3
  export type RelationDiff = {
4
4
  toAdd: BeforeOperationRelation[];
5
- toDelete: Relation[];
6
- toUpdate: Relation[];
5
+ toDelete: RelationRow[];
6
+ toUpdate: RelationRow[];
7
7
  };
8
8
  type Args = {
9
- existingRelations: Relation[];
9
+ existingRelations: RelationRow[];
10
10
  incomingRelations: BeforeOperationRelation[];
11
11
  locale?: string;
12
12
  };
@@ -1,5 +1,6 @@
1
1
  import { RelationFieldBuilder } from '../../../../fields/relation/index.js';
2
- import { getValueAtPath } from '../../../../util/object.js';
2
+ import { Relation } from '../../../../fields/relation/relation.js';
3
+ import { getValueAtPath, isObjectLiteral } from '../../../../util/object.js';
3
4
  export const extractRelations = ({ ownerId, data, configMap, locale }) => {
4
5
  const relations = [];
5
6
  // The config map keys every field the document holds; relations are the ones stored as junction
@@ -7,55 +8,36 @@ export const extractRelations = ({ ownerId, data, configMap, locale }) => {
7
8
  for (const [path, config] of Object.entries(configMap)) {
8
9
  if (config instanceof RelationFieldBuilder) {
9
10
  const value = getValueAtPath(path, data);
10
- const localized = config.get.localized;
11
- const relationRawValue = value;
12
- let output = [];
13
- const relationFromString = ({ value, position = 0 }) => {
14
- const result = {
11
+ // One value outside an array is a list of one.
12
+ const entries = Array.isArray(value) ? value : value ? [value] : [];
13
+ // A bare id, a ref, or a document read at depth 1 and sent back. Anything else, a `null`
14
+ // element included, names nothing.
15
+ const named = entries.flatMap((entry) => {
16
+ const documentId = documentIdOf(entry);
17
+ return documentId ? [{ entry, documentId }] : [];
18
+ });
19
+ named.forEach(({ entry, documentId }, position) => {
20
+ relations.push({
21
+ // A ref's own row, so the stored row is updated rather than replaced.
22
+ id: Relation.isRef(entry) ? entry.id || undefined : undefined,
15
23
  position,
16
24
  relationTo: config.get.relationTo,
17
- documentId: value,
25
+ documentId,
18
26
  ownerId,
19
- path
20
- };
21
- if (localized) {
22
- result.locale = locale;
23
- }
24
- return result;
25
- };
26
- const completeRelation = ({ value, position = 0 }) => {
27
- const result = {
28
- id: value.id || undefined,
29
- position,
30
- relationTo: config.get.relationTo,
31
- documentId: value.documentId,
32
- ownerId,
33
- path
34
- };
35
- if (localized) {
36
- result.locale = locale;
37
- }
38
- return result;
39
- };
40
- // If value is array
41
- if (Array.isArray(relationRawValue)) {
42
- output = relationRawValue.map((value, n) => {
43
- // Array of string build the relation value
44
- if (typeof value === 'string') {
45
- return relationFromString({ value, position: n });
46
- }
47
- else {
48
- // Complete possible missing props
49
- return completeRelation({ value, position: n });
50
- }
27
+ path,
28
+ ...(config.get.localized && { locale })
51
29
  });
52
- // Check if it's a string
53
- }
54
- else if (typeof relationRawValue === 'string') {
55
- output = [relationFromString({ value: relationRawValue, position: 0 })];
56
- }
57
- relations.push(...output);
30
+ });
58
31
  }
59
32
  }
60
33
  return relations;
61
34
  };
35
+ const documentIdOf = (entry) => {
36
+ if (typeof entry === 'string')
37
+ return entry || null;
38
+ if (Relation.isRef(entry))
39
+ return entry.documentId;
40
+ if (isObjectLiteral(entry) && typeof entry.id === 'string')
41
+ return entry.id;
42
+ return null;
43
+ };
@@ -3,6 +3,7 @@ import type { RegisterArea } from '../../../index.js';
3
3
  import type { PrototypeApiContext } from '../define.js';
4
4
  import type { RequestEvent } from '@sveltejs/kit';
5
5
  import type { Dic } from '../../../util/types.js';
6
+ import type { WithRelationResolved } from '../../fields/types.js';
6
7
  import type { GenericDoc } from '../types.js';
7
8
  import type { OperationQuery } from '../../pipeline/types.js';
8
9
  import { type FindArgs } from './operations/find.js';
@@ -65,8 +66,13 @@ declare class AreaAPI<Doc extends GenericDoc> implements PrototypeApiContext<Bui
65
66
  * const doc = await rime.area('settings').find({ locale })
66
67
  * const doc = await rime.area('settings').find({ versionId: '123' })
67
68
  * const doc = await rime.area('settings').find({ latest: true })
69
+ *
70
+ * // A literal `depth` types the relations resolved: `doc.logo` is `MediasDoc[]`
71
+ * const doc = await rime.area('settings').find({ depth: 1 })
68
72
  */
69
- find(args?: FindArgs): Promise<Doc>;
73
+ find<D extends number = 0>(args?: FindArgs & {
74
+ depth?: D;
75
+ }): Promise<WithRelationResolved<Doc, D>>;
70
76
  /**
71
77
  * Updates the area's document
72
78
  *
@@ -74,6 +74,9 @@ class AreaAPI {
74
74
  * const doc = await rime.area('settings').find({ locale })
75
75
  * const doc = await rime.area('settings').find({ versionId: '123' })
76
76
  * const doc = await rime.area('settings').find({ latest: true })
77
+ *
78
+ * // A literal `depth` types the relations resolved: `doc.logo` is `MediasDoc[]`
79
+ * const doc = await rime.area('settings').find({ depth: 1 })
77
80
  */
78
81
  find(args = {}) {
79
82
  const { locale, select = [], depth = 0, versionId, latest, localeFallback } = args;
@@ -1,9 +1,10 @@
1
1
  import type { BuiltArea } from '../../../config/types.js';
2
2
  import type { PrototypeApiContext } from '../../define.js';
3
3
  import type { GenericDoc } from '../../types.js';
4
+ import type { WithRelationInput } from '../../../fields/types.js';
4
5
  import type { DeepPartial } from '../../../../util/types.js';
5
6
  export type UpdateArgs<T> = {
6
- data: DeepPartial<T>;
7
+ data: DeepPartial<WithRelationInput<T>>;
7
8
  locale?: string | undefined;
8
9
  versionId?: string;
9
10
  /** Start from the newest version rather than the published one. `PARAMS.LATEST`. */
@@ -3,6 +3,7 @@ import type { RegisterCollection } from '../../../index.js';
3
3
  import type { PrototypeApiContext } from '../define.js';
4
4
  import type { RequestEvent } from '@sveltejs/kit';
5
5
  import type { Dic } from '../../../util/types.js';
6
+ import type { WithRelationResolved } from '../../fields/types.js';
6
7
  import type { CollectionSlug } from '../types.js';
7
8
  import type { OperationQuery } from '../../pipeline/types.js';
8
9
  import { type CreateArgs } from './operations/create.js';
@@ -99,8 +100,13 @@ declare class CollectionAPI<Doc extends RegisterCollection[CollectionSlug]> impl
99
100
  * sort: '-createdAt',
100
101
  * limit: 10
101
102
  * });
103
+ *
104
+ * // A literal `depth` types the relations resolved: `posts[0].author` is `UsersDoc[]`
105
+ * const posts = await rime.collection('posts').find({ depth: 1 });
102
106
  */
103
- find(args?: FindArgs): Promise<Doc[]>;
107
+ find<D extends number = 0>(args?: FindArgs & {
108
+ depth?: D;
109
+ }): Promise<WithRelationResolved<Doc, D>[]>;
104
110
  /**
105
111
  * Finds a document in the collection by ID
106
112
  *
@@ -125,8 +131,13 @@ declare class CollectionAPI<Doc extends RegisterCollection[CollectionSlug]> impl
125
131
  * id: '12345',
126
132
  * latest: true
127
133
  * });
134
+ *
135
+ * // A literal `depth` types the relations resolved: `post.author` is `UsersDoc[]`
136
+ * const post = await rime.collection('posts').findById({ id: '12345', depth: 1 });
128
137
  */
129
- findById(args: FindByIdArgs): Promise<Doc>;
138
+ findById<D extends number = 0>(args: FindByIdArgs & {
139
+ depth?: D;
140
+ }): Promise<WithRelationResolved<Doc, D>>;
130
141
  /**
131
142
  * Finds the documents with these ids, in one read. Each id is checked against the read access
132
143
  * as findById would check it; a missing or refused one is left out. The order is the list's
@@ -135,7 +146,9 @@ declare class CollectionAPI<Doc extends RegisterCollection[CollectionSlug]> impl
135
146
  * @example
136
147
  * const medias = await rime.collection('medias').findByIds({ ids: ['a1', 'b2'] });
137
148
  */
138
- findByIds(args: FindByIdsArgs): Promise<Doc[]>;
149
+ findByIds<D extends number = 0>(args: FindByIdsArgs & {
150
+ depth?: D;
151
+ }): Promise<WithRelationResolved<Doc, D>[]>;
139
152
  /**
140
153
  * Changes a page's slug in one locale, on the published page. Its address changes, and the pages
141
154
  * under it follow. A collection with `$url` only.
@@ -120,6 +120,9 @@ class CollectionAPI {
120
120
  * sort: '-createdAt',
121
121
  * limit: 10
122
122
  * });
123
+ *
124
+ * // A literal `depth` types the relations resolved: `posts[0].author` is `UsersDoc[]`
125
+ * const posts = await rime.collection('posts').find({ depth: 1 });
123
126
  */
124
127
  find(args = {}) {
125
128
  const { query, locale, sort = '-updatedAt', depth = 0, limit, offset, latest, select, localeFallback } = args;
@@ -163,6 +166,9 @@ class CollectionAPI {
163
166
  * id: '12345',
164
167
  * latest: true
165
168
  * });
169
+ *
170
+ * // A literal `depth` types the relations resolved: `post.author` is `UsersDoc[]`
171
+ * const post = await rime.collection('posts').findById({ id: '12345', depth: 1 });
166
172
  */
167
173
  findById(args) {
168
174
  const { id, versionId, locale, select, latest, depth = 0, localeFallback } = args;
@@ -2,13 +2,14 @@ import type { BuiltCollection } from '../../../config/types.js';
2
2
  import type { PrototypeApiContext } from '../../define.js';
3
3
  import type { CollectionSlug } from '../../types.js';
4
4
  import type { RegisterCollection } from '../../../../index.js';
5
+ import type { WithRelationInput } from '../../../fields/types.js';
5
6
  import type { DeepPartial } from '../../../../util/types.js';
6
7
  /**
7
8
  * What a caller passes. Exported, and free of the context, so the API surface a prototype
8
9
  * declares never mentions the request — see the note on `CollectionApi`.
9
10
  */
10
11
  export type CreateArgs<T> = {
11
- data: DeepPartial<T>;
12
+ data: DeepPartial<WithRelationInput<T>>;
12
13
  locale?: string | undefined;
13
14
  };
14
15
  type Args<T> = CreateArgs<T> & {
@@ -26,9 +26,11 @@ export const deleteDocs = async (args) => {
26
26
  const collection = isSystemOperation
27
27
  ? rime.collection(config.slug).system()
28
28
  : rime.collection(config.slug);
29
- const promisesDelete = documentsToDelete.map(({ id }) => {
30
- return collection.deleteById({ id });
31
- });
32
- const ids = await Promise.all(promisesDelete);
29
+ // One after the other: rows sharing an uploaded file each check whether another still uses it,
30
+ // and the last one deleted is the one that finds none and removes the file.
31
+ const ids = [];
32
+ for (const { id } of documentsToDelete) {
33
+ ids.push(await collection.deleteById({ id }));
34
+ }
33
35
  return ids;
34
36
  };
@@ -1,5 +1,5 @@
1
1
  import { copyLocales } from '../../../locale/copy.server.js';
2
- import { isJSONContent, richTextJSONToText } from '../../../../fields/rich-text/json.js';
2
+ import { isJSONContent, RichText } from '../../../../fields/rich-text/json.js';
3
3
  import { getValueAtPath, isObjectLiteral, setValueAtPath } from '../../../../util/object.js';
4
4
  // If block is localized should not keep its id so it created a new one
5
5
  // If block is not localized than it should keep its id so block is updated
@@ -21,9 +21,7 @@ export const duplicate = async (args) => {
21
21
  return doc;
22
22
  const getTitle = () => {
23
23
  const title = getValueAtPath(config.asTitle, doc);
24
- return isJSONContent(title)
25
- ? richTextJSONToText(title) + ' (copy)'
26
- : title + ' (copy)';
24
+ return isJSONContent(title) ? RichText.toText(title) + ' (copy)' : title + ' (copy)';
27
25
  };
28
26
  const data = setValueAtPath(config.asTitle, doc, getTitle());
29
27
  return data;
@@ -1,6 +1,7 @@
1
1
  import type { BuiltCollection } from '../../../config/types.js';
2
2
  import type { PrototypeApiContext } from '../../define.js';
3
3
  import type { GenericDoc } from '../../types.js';
4
+ import type { WithRelationInput } from '../../../fields/types.js';
4
5
  import type { DeepPartial } from '../../../../util/types.js';
5
6
  export type UpdateByIdArgs<T> = {
6
7
  id: string;
@@ -11,7 +12,7 @@ export type UpdateByIdArgs<T> = {
11
12
  fork?: boolean;
12
13
  /** Write the caller's auto-saved row of the version `versionId` names. Panel only. */
13
14
  autoSave?: boolean;
14
- data: DeepPartial<T>;
15
+ data: DeepPartial<WithRelationInput<T>>;
15
16
  locale?: string | undefined;
16
17
  /** This write copies another locale's rows onto the row — see `copyLocales`. */
17
18
  isLocaleCopy?: boolean;
@@ -1,5 +1,5 @@
1
1
  import { Hooks } from '../../../../pipeline/define-hook.js';
2
- import { isRelationResolved } from '../../../../../fields/relation/util.js';
2
+ import { Relation } from '../../../../../fields/relation/relation.js';
3
3
  import {} from '../../../../../types.js';
4
4
  import { getValueAtPath } from '../../../../../util/object.js';
5
5
  /**
@@ -20,21 +20,15 @@ export const setDocumentThumbnail = Hooks.beforeRead(async (args) => {
20
20
  !doc._thumbnail &&
21
21
  (!hasSelect || (hasSelect && paramSelect.includes('_thumbnail')));
22
22
  if (shouldSetThumbnail) {
23
- const relationValue = getValueAtPath(config.asThumbnail, doc);
24
- if (!relationValue || (Array.isArray(relationValue) && relationValue.length === 0))
23
+ // At depth 0 the relation holds a ref to the media; at depth 1 or more, the media itself.
24
+ const [first] = getValueAtPath(config.asThumbnail, doc) ?? [];
25
+ if (!first)
25
26
  return args;
26
- const unwraped = Array.isArray(relationValue) ? relationValue[0] : relationValue;
27
- if (typeof unwraped === 'string')
28
- return args;
29
- const relationResolved = isRelationResolved(unwraped)
30
- ? unwraped
31
- : await args.event.locals.rime
32
- .collection(unwraped.relationTo)
33
- .findById({ id: unwraped.documentId });
34
- doc = {
35
- _thumbnail: relationResolved._thumbnail,
36
- ...doc
37
- };
27
+ const readMedia = (ref) => args.event.locals.rime
28
+ .collection(ref.relationTo)
29
+ .findById({ id: ref.documentId });
30
+ const media = Relation.isRef(first) ? await readMedia(first) : first;
31
+ doc = { _thumbnail: media._thumbnail, ...doc };
38
32
  }
39
33
  return { ...args, doc };
40
34
  });
@@ -50,7 +50,7 @@ const isFilenameStillReferenced = async (args) => {
50
50
  for (const slug of targetSlugs) {
51
51
  for (const locale of localesToQuery) {
52
52
  const docs = await rime.collection(slug).find({
53
- query: `where[filename][equals]=${filename}`,
53
+ query: `where[filename][equals]=${encodeURIComponent(filename)}`,
54
54
  latest: true,
55
55
  locale,
56
56
  limit: slug === selfSlug ? 2 : 1
@@ -1,5 +1,5 @@
1
1
  import { Hooks } from '../../../../pipeline/define-hook.js';
2
- import { richTextJSONToText } from '../../../../../fields/rich-text/json.js';
2
+ import { RichText } from '../../../../../fields/rich-text/json.js';
3
3
  import { getValueAtPath, isObjectLiteral } from '../../../../../util/object.js';
4
4
  /**
5
5
  * Puts `title` on the document, read from whichever field `asTitle` resolved to.
@@ -14,7 +14,7 @@ export const setDocumentTitle = Hooks.beforeRead(async function setDocumentTitle
14
14
  function computeTitleFromValue(value) {
15
15
  // Handle rich text value
16
16
  if (isObjectLiteral(value) && 'content' in value) {
17
- return richTextJSONToText(value);
17
+ return RichText.toText(value);
18
18
  }
19
19
  if (typeof value === 'string') {
20
20
  return value;