@eightyfourthousand/data-access 2026.3.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 (91) hide show
  1. package/.babelrc +12 -0
  2. package/.eslintrc.json +18 -0
  3. package/README.md +7 -0
  4. package/jest.config.ts +10 -0
  5. package/package.json +30 -0
  6. package/project.json +21 -0
  7. package/src/index.ts +18 -0
  8. package/src/lib/auth.ts +203 -0
  9. package/src/lib/bibliography.ts +57 -0
  10. package/src/lib/canon.ts +111 -0
  11. package/src/lib/client-browser.ts +12 -0
  12. package/src/lib/client-server.ts +30 -0
  13. package/src/lib/client-ssr.ts +24 -0
  14. package/src/lib/client-token.ts +24 -0
  15. package/src/lib/feedback.ts +71 -0
  16. package/src/lib/folio.ts +43 -0
  17. package/src/lib/glossary.ts +147 -0
  18. package/src/lib/imprint.ts +42 -0
  19. package/src/lib/library.ts +209 -0
  20. package/src/lib/local-storage.ts +33 -0
  21. package/src/lib/lookup-entity.ts +122 -0
  22. package/src/lib/panel-url.ts +43 -0
  23. package/src/lib/passage.ts +122 -0
  24. package/src/lib/projects.ts +107 -0
  25. package/src/lib/proxy.ts +68 -0
  26. package/src/lib/publications.ts +213 -0
  27. package/src/lib/storage.ts +23 -0
  28. package/src/lib/types/alignment.ts +32 -0
  29. package/src/lib/types/annotation/abbreviation.ts +30 -0
  30. package/src/lib/types/annotation/annotation-type.ts +219 -0
  31. package/src/lib/types/annotation/annotation.ts +244 -0
  32. package/src/lib/types/annotation/audio.ts +33 -0
  33. package/src/lib/types/annotation/blockquote.ts +18 -0
  34. package/src/lib/types/annotation/code.ts +16 -0
  35. package/src/lib/types/annotation/deprecated.ts +18 -0
  36. package/src/lib/types/annotation/end-note-link.ts +35 -0
  37. package/src/lib/types/annotation/export.ts +69 -0
  38. package/src/lib/types/annotation/glossary-instance.ts +34 -0
  39. package/src/lib/types/annotation/has-abbreviation.ts +30 -0
  40. package/src/lib/types/annotation/heading.ts +37 -0
  41. package/src/lib/types/annotation/image.ts +29 -0
  42. package/src/lib/types/annotation/indent.ts +16 -0
  43. package/src/lib/types/annotation/index.ts +4 -0
  44. package/src/lib/types/annotation/inline-title.ts +34 -0
  45. package/src/lib/types/annotation/internal-link.ts +86 -0
  46. package/src/lib/types/annotation/leading-space.ts +18 -0
  47. package/src/lib/types/annotation/line-group.ts +18 -0
  48. package/src/lib/types/annotation/line.ts +16 -0
  49. package/src/lib/types/annotation/link.ts +38 -0
  50. package/src/lib/types/annotation/list-item.ts +16 -0
  51. package/src/lib/types/annotation/list.ts +43 -0
  52. package/src/lib/types/annotation/mantra.ts +31 -0
  53. package/src/lib/types/annotation/mention.ts +64 -0
  54. package/src/lib/types/annotation/paragraph.ts +18 -0
  55. package/src/lib/types/annotation/quote.ts +30 -0
  56. package/src/lib/types/annotation/quoted.ts +30 -0
  57. package/src/lib/types/annotation/reference.ts +18 -0
  58. package/src/lib/types/annotation/span.ts +39 -0
  59. package/src/lib/types/annotation/table-body-data.ts +18 -0
  60. package/src/lib/types/annotation/table-body-header.ts +18 -0
  61. package/src/lib/types/annotation/table-body-row.ts +18 -0
  62. package/src/lib/types/annotation/table.ts +16 -0
  63. package/src/lib/types/annotation/trailer.ts +16 -0
  64. package/src/lib/types/annotation/transform.ts +140 -0
  65. package/src/lib/types/annotation/unknown.ts +16 -0
  66. package/src/lib/types/bibliography.ts +86 -0
  67. package/src/lib/types/canon.ts +148 -0
  68. package/src/lib/types/client.ts +3 -0
  69. package/src/lib/types/contributor.ts +84 -0
  70. package/src/lib/types/editor-content.ts +21 -0
  71. package/src/lib/types/folio.ts +28 -0
  72. package/src/lib/types/glossary-page.ts +204 -0
  73. package/src/lib/types/glossary.ts +114 -0
  74. package/src/lib/types/imprint.ts +159 -0
  75. package/src/lib/types/index.ts +22 -0
  76. package/src/lib/types/language.ts +64 -0
  77. package/src/lib/types/layout.ts +37 -0
  78. package/src/lib/types/library.ts +29 -0
  79. package/src/lib/types/passage.ts +220 -0
  80. package/src/lib/types/project.ts +200 -0
  81. package/src/lib/types/semver.ts +1 -0
  82. package/src/lib/types/title.ts +47 -0
  83. package/src/lib/types/toh.ts +1 -0
  84. package/src/lib/types/translation.ts +15 -0
  85. package/src/lib/types/user.ts +15 -0
  86. package/src/lib/types/work.ts +38 -0
  87. package/src/lib/use-bookmark.ts +45 -0
  88. package/src/ssr.ts +5 -0
  89. package/tsconfig.json +20 -0
  90. package/tsconfig.lib.json +26 -0
  91. package/tsconfig.spec.json +22 -0
@@ -0,0 +1,122 @@
1
+ import {
2
+ ANNOTATIONS_TO_IGNORE,
3
+ DataClient,
4
+ Passage,
5
+ PassageDTO,
6
+ annotationsFromDTO,
7
+ passageFromDTO,
8
+ passagesToDTO,
9
+ passagesToRowDTO,
10
+ } from './types';
11
+
12
+ export const getPassage = async ({
13
+ client,
14
+ uuid,
15
+ }: {
16
+ client: DataClient;
17
+ uuid: string;
18
+ }) => {
19
+ const { data } = await client
20
+ .rpc('get_passage_with_annotations', {
21
+ uuid_input: uuid,
22
+ })
23
+ .single();
24
+
25
+ if (!data) {
26
+ console.warn(`No passage found for uuid: ${uuid}`);
27
+ return undefined;
28
+ }
29
+
30
+ const dto = data as PassageDTO;
31
+ return passageFromDTO(
32
+ dto,
33
+ annotationsFromDTO(dto?.annotations || [], dto?.content.length || 0),
34
+ );
35
+ };
36
+
37
+ export const getPassageUuidByXmlId = async ({
38
+ client,
39
+ xmlId,
40
+ }: {
41
+ client: DataClient;
42
+ xmlId: string;
43
+ }) => {
44
+ const { data, error } = await client
45
+ .from('passages')
46
+ .select('uuid, workUuid:work_uuid')
47
+ .eq('xmlId', xmlId)
48
+ .single();
49
+
50
+ if (error) {
51
+ console.error(`Error fetching passage uuid for xmlId: ${xmlId}`, error);
52
+ return;
53
+ }
54
+
55
+ return data?.uuid;
56
+ };
57
+
58
+ export const savePassages = async ({
59
+ client,
60
+ passages,
61
+ }: {
62
+ client: DataClient;
63
+ passages: Passage[];
64
+ }) => {
65
+ /**
66
+ * 1. Extract all annotations from savePassages
67
+ * 2. Query the database for all current annotations for the savePassages
68
+ * 3. Determine which annotations need to be deleted or upserted
69
+ * 4. Upsert the passages
70
+ * 5. Upsert the annotations
71
+ * 6. Delete the annotations that are no longer present
72
+ */
73
+ const dtos = passagesToDTO(passages);
74
+ const passageRowDtos = passagesToRowDTO(passages);
75
+ const passageUuids = passages.map((p) => p.uuid);
76
+ const annotations = dtos.flatMap((p) => p.annotations || []);
77
+
78
+ const { data: existingAnnotations } = await client
79
+ .from('passage_annotations')
80
+ .select(`uuid`)
81
+ .in('passage_uuid', passageUuids)
82
+ .not('type', 'in', `(${ANNOTATIONS_TO_IGNORE.join(',')})`);
83
+
84
+ const annotationsToDelete = existingAnnotations?.filter(
85
+ (ea) => !annotations.find((a) => a.uuid === ea.uuid),
86
+ );
87
+
88
+ const { error: passageError } = await client
89
+ .from('passages')
90
+ .upsert(passageRowDtos, { onConflict: 'uuid' });
91
+
92
+ if (passageError) {
93
+ console.error('Error saving passages:', passageError);
94
+ return;
95
+ }
96
+
97
+ if (annotations.length > 0) {
98
+ const { error: annotationError } = await client
99
+ .from('passage_annotations')
100
+ .upsert(annotations, { onConflict: 'uuid' });
101
+
102
+ if (annotationError) {
103
+ console.error('Error saving annotations:', annotationError);
104
+ throw annotationError;
105
+ }
106
+ }
107
+
108
+ if (annotationsToDelete && annotationsToDelete.length > 0) {
109
+ const { error: deleteError } = await client
110
+ .from('passage_annotations')
111
+ .delete()
112
+ .in(
113
+ 'uuid',
114
+ annotationsToDelete.map((a) => a.uuid),
115
+ );
116
+
117
+ if (deleteError) {
118
+ console.error('Error deleting annotations:', deleteError);
119
+ throw deleteError;
120
+ }
121
+ }
122
+ };
@@ -0,0 +1,107 @@
1
+ import {
2
+ DataClient,
3
+ ProjectContributor,
4
+ ProjectContributorsDTO,
5
+ projectContributorsFromDTO,
6
+ } from './types';
7
+ import {
8
+ Project,
9
+ ProjectAsset,
10
+ ProjectStageDetail,
11
+ ProjectStageDetailsDTO,
12
+ ProjectTableDTO,
13
+ ProjectViewDTO,
14
+ projectFromTableDTO,
15
+ projectFromViewDTO,
16
+ projectStageDetailsFromDTO,
17
+ } from './types/project';
18
+
19
+ export const getProjects = async ({ client }: { client: DataClient }) => {
20
+ const { data } = await client.rpc('get_projects');
21
+
22
+ const dtos = (data as ProjectViewDTO[]) || [];
23
+ const projects = dtos.map(projectFromViewDTO);
24
+
25
+ return { projects };
26
+ };
27
+
28
+ export const getProjectByUuid = async ({
29
+ client,
30
+ uuid,
31
+ }: {
32
+ client: DataClient;
33
+ uuid: string;
34
+ }): Promise<Project> => {
35
+ const { data } = await client.rpc('get_project', { uuid_input: uuid });
36
+
37
+ return projectFromTableDTO(data as ProjectTableDTO);
38
+ };
39
+
40
+ export const getProjectStages = async ({
41
+ client,
42
+ uuid,
43
+ }: {
44
+ client: DataClient;
45
+ uuid: string;
46
+ }): Promise<ProjectStageDetail[]> => {
47
+ const { data } = await client.rpc('get_project_stages', { uuid_input: uuid });
48
+ return projectStageDetailsFromDTO(data as ProjectStageDetailsDTO[]);
49
+ };
50
+
51
+ export const getProjectAssets = async ({
52
+ client,
53
+ projectUuid,
54
+ stageUuid,
55
+ }: {
56
+ client: DataClient;
57
+ projectUuid?: string;
58
+ stageUuid?: string;
59
+ }): Promise<ProjectAsset[]> => {
60
+ if (!projectUuid && !stageUuid) {
61
+ console.error('One of projectUuid or stageUuid is required');
62
+ return [];
63
+ }
64
+
65
+ const { data } = await client.rpc('get_project_assets', {
66
+ project_uuid_input: projectUuid,
67
+ stage_uuid_input: stageUuid,
68
+ });
69
+ return data || [];
70
+ };
71
+
72
+ export const getProjectContributors = async ({
73
+ client,
74
+ projectUuid,
75
+ stageUuid,
76
+ }: {
77
+ client: DataClient;
78
+ projectUuid?: string;
79
+ stageUuid?: string;
80
+ }): Promise<ProjectContributor[]> => {
81
+ if (!projectUuid && !stageUuid) {
82
+ console.error('One of projectUuid or stageUuid is required');
83
+ return [];
84
+ }
85
+
86
+ const uuid = stageUuid ? stageUuid : projectUuid;
87
+ const key = stageUuid ? 'stage_uuid' : 'project_uuid';
88
+
89
+ const { data } = await client
90
+ .from('project_contributors')
91
+ .select(
92
+ `
93
+ uuid,
94
+ stageUuid:stage_uuid,
95
+ projectUuid:project_uuid,
96
+ ...authorities!contributor_uuid(
97
+ contributorUuid:uuid,
98
+ name:headword
99
+ ),
100
+ startDate:start_date,
101
+ endDate:end_date,
102
+ role:type
103
+ `,
104
+ )
105
+ .eq(key, uuid);
106
+ return projectContributorsFromDTO(data as ProjectContributorsDTO);
107
+ };
@@ -0,0 +1,68 @@
1
+ import { createServerClient } from '@supabase/ssr';
2
+ import { jwtDecode } from 'jwt-decode';
3
+ import { NextResponse, type NextRequest } from 'next/server';
4
+ import { UserRole } from './types';
5
+
6
+ export async function updateSession(request: NextRequest) {
7
+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
8
+ const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
9
+
10
+ if (!supabaseUrl || !supabaseAnonKey) {
11
+ throw new Error('Missing Supabase credentials');
12
+ }
13
+ let supabaseResponse = NextResponse.next({
14
+ request,
15
+ });
16
+
17
+ const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
18
+ cookies: {
19
+ getAll() {
20
+ return request.cookies.getAll();
21
+ },
22
+ setAll(
23
+ cookiesToSet: Array<{
24
+ name: string;
25
+ value: string;
26
+ options?: Record<string, unknown>;
27
+ }>,
28
+ ) {
29
+ cookiesToSet.forEach(({ name, value }) =>
30
+ request.cookies.set(name, value),
31
+ );
32
+ supabaseResponse = NextResponse.next({
33
+ request,
34
+ });
35
+ cookiesToSet.forEach(({ name, value, options }) =>
36
+ supabaseResponse.cookies.set(name, value, options),
37
+ );
38
+ },
39
+ },
40
+ });
41
+
42
+ // Do not run code between update and
43
+ // supabase.auth.getUser(). A simple mistake could make it very hard to debug
44
+ // issues with users being randomly logged out.
45
+
46
+ // IMPORTANT: DO NOT REMOVE auth.getUser()
47
+
48
+ const {
49
+ data: { user },
50
+ } = await supabase.auth.getUser();
51
+
52
+ const {
53
+ data: { session },
54
+ } = await supabase.auth.getSession();
55
+ let role: UserRole = 'reader';
56
+ if (session?.access_token) {
57
+ try {
58
+ const { user_role: userRole } = jwtDecode(session.access_token) as {
59
+ user_role: string;
60
+ };
61
+ role = (userRole as UserRole) || 'reader';
62
+ } catch (error) {
63
+ console.error('Failed to decode JWT:', error);
64
+ }
65
+ }
66
+
67
+ return { user, role, supabaseResponse };
68
+ }
@@ -0,0 +1,213 @@
1
+ import {
2
+ BodyItemType,
3
+ DataClient,
4
+ TitlesDTO,
5
+ WorkDTO,
6
+ titlesFromDTO,
7
+ workFromDTO,
8
+ passagesPageFromDTO,
9
+ PassagesPageDTO,
10
+ PassagesPage,
11
+ PaginationDirection,
12
+ passagesPageAroundFromDTO,
13
+ PassagesPageAroundDTO,
14
+ Work,
15
+ } from './types';
16
+
17
+ export const getTranslationUuids = async ({
18
+ client,
19
+ }: {
20
+ client: DataClient;
21
+ }): Promise<string[]> => {
22
+ const { data } = await client.rpc('get_static_translation_uuids');
23
+ return data?.map(({ uuid }: { uuid: string }) => uuid) || [];
24
+ };
25
+
26
+ export const getTranslationPassages = async ({
27
+ client,
28
+ uuid,
29
+ type,
30
+ cursor,
31
+ maxPassages,
32
+ maxCharacters,
33
+ direction,
34
+ }: {
35
+ client: DataClient;
36
+ uuid: string;
37
+ type?: BodyItemType;
38
+ cursor?: string;
39
+ maxPassages?: number;
40
+ maxCharacters?: number;
41
+ direction?: PaginationDirection;
42
+ }): Promise<PassagesPage> => {
43
+ const { data, error } = await client.rpc('get_passages_page', {
44
+ uuid_input: uuid,
45
+ passage_type_input: type,
46
+ cursor,
47
+ max_passages: maxPassages,
48
+ char_budget: maxCharacters,
49
+ direction,
50
+ });
51
+
52
+ if (error) {
53
+ console.error('Error fetching translation passages:', error);
54
+ return {
55
+ hasMoreAfter: false,
56
+ hasMoreBefore: false,
57
+ passages: [],
58
+ };
59
+ }
60
+
61
+ return passagesPageFromDTO(direction || 'forward', data as PassagesPageDTO);
62
+ };
63
+
64
+ export const getTranslationPassagesAround = async ({
65
+ client,
66
+ uuid,
67
+ passageUuid,
68
+ type,
69
+ maxPassages,
70
+ maxCharacters,
71
+ }: {
72
+ client: DataClient;
73
+ uuid: string;
74
+ passageUuid: string;
75
+ type?: BodyItemType;
76
+ maxPassages?: number;
77
+ maxCharacters?: number;
78
+ }): Promise<PassagesPage> => {
79
+ const { data, error } = await client.rpc('get_passages_page_around', {
80
+ uuid_input: uuid,
81
+ cursor: passageUuid,
82
+ passage_type_input: type,
83
+ max_passages: maxPassages,
84
+ char_budget: maxCharacters,
85
+ });
86
+
87
+ if (error) {
88
+ console.error('Error fetching translation passages around:', error);
89
+ return {
90
+ hasMoreAfter: false,
91
+ hasMoreBefore: false,
92
+ passages: [],
93
+ };
94
+ }
95
+
96
+ return passagesPageAroundFromDTO(data as PassagesPageAroundDTO);
97
+ };
98
+
99
+ export const getTranslationTitles = async ({
100
+ client,
101
+ uuid,
102
+ }: {
103
+ client: DataClient;
104
+ uuid: string;
105
+ }) => {
106
+ const { data } = await client.rpc('get_work_titles', {
107
+ work_uuid_input: uuid,
108
+ });
109
+
110
+ return titlesFromDTO(data as TitlesDTO);
111
+ };
112
+
113
+ export const getTranslationMetadataByUuid = async ({
114
+ client,
115
+ uuid,
116
+ }: {
117
+ client: DataClient;
118
+ uuid: string;
119
+ }) => {
120
+ const { data, error } = await client
121
+ .from('works')
122
+ .select(
123
+ `
124
+ uuid,
125
+ title,
126
+ description,
127
+ tohs:work_toh!inner(toh:toh_clean),
128
+ publicationDate,
129
+ publicationVersion,
130
+ pages:source_pages,
131
+ restriction,
132
+ breadcrumb
133
+ `,
134
+ )
135
+ .eq('uuid', uuid)
136
+ .single();
137
+
138
+ if (error) {
139
+ throw new Error(
140
+ `Error fetching translation metadata by UUID: ${error.message}`,
141
+ );
142
+ }
143
+
144
+ return workFromDTO(data as WorkDTO);
145
+ };
146
+
147
+ export const getTranslationMetadataByToh = async ({
148
+ client,
149
+ toh,
150
+ }: {
151
+ client: DataClient;
152
+ toh: string;
153
+ }) => {
154
+ const { data, error } = await client
155
+ .from('work_toh')
156
+ .select(
157
+ `
158
+ work_uuid,
159
+ works!inner(
160
+ uuid,
161
+ title,
162
+ description,
163
+ tohs:work_toh!inner(toh:toh_clean),
164
+ publicationDate,
165
+ publicationVersion,
166
+ pages:source_pages,
167
+ restriction,
168
+ breadcrumb
169
+ )
170
+ `,
171
+ )
172
+ .eq('toh_clean', toh)
173
+ .single();
174
+
175
+ // Extract the work data from the joined result
176
+ const workData = data?.works as WorkDTO | undefined;
177
+ if (error || !workData) {
178
+ console.error('Error fetching translation metadata by TOH:', error);
179
+ return null;
180
+ }
181
+
182
+ return workFromDTO(workData);
183
+ };
184
+
185
+ export const getTranslationsMetadata = async ({
186
+ client,
187
+ }: {
188
+ client: DataClient;
189
+ }): Promise<Work[]> => {
190
+ const { data, error } = await client
191
+ .from('works')
192
+ .select(
193
+ `
194
+ uuid,
195
+ title,
196
+ description,
197
+ tohs:work_toh!inner(toh:toh_clean),
198
+ publicationDate,
199
+ publicationVersion,
200
+ pages:source_pages,
201
+ restriction,
202
+ breadcrumb
203
+ `,
204
+ )
205
+ .not('toh', 'like', 'toh00%');
206
+ if (error) {
207
+ console.error('Error fetching translations metadata:', error);
208
+ return [];
209
+ }
210
+
211
+ const dto = data as WorkDTO[];
212
+ return dto?.map((work) => workFromDTO(work as WorkDTO)) || [];
213
+ };
@@ -0,0 +1,23 @@
1
+ import { DataClient } from './types';
2
+
3
+ export const uploadToStorage = async ({
4
+ client,
5
+ bucket,
6
+ path,
7
+ file,
8
+ }: {
9
+ client: DataClient;
10
+ bucket: string;
11
+ path: string;
12
+ file: File;
13
+ }) => {
14
+ const { error } = await client.storage.from(bucket).upload(path, file);
15
+
16
+ if (error) {
17
+ console.error('Error uploading to storage:', error);
18
+ return null;
19
+ }
20
+
21
+ const { data } = client.storage.from(bucket).getPublicUrl(path);
22
+ return data.publicUrl;
23
+ };
@@ -0,0 +1,32 @@
1
+ import { TohokuCatalogEntry } from './toh';
2
+
3
+ export type AlignmentDTO = {
4
+ passage_uuid: string;
5
+ folio_uuid: string;
6
+ toh: TohokuCatalogEntry;
7
+ tibetan: string;
8
+ folio_number: number;
9
+ volume_number: number;
10
+ };
11
+
12
+ export type Alignment = {
13
+ folioUuid: string;
14
+ toh: TohokuCatalogEntry;
15
+ tibetan: string;
16
+ folioNumber: number;
17
+ volumeNumber: number;
18
+ };
19
+
20
+ export const alignmentFromDTO = (dto: AlignmentDTO): Alignment => {
21
+ return {
22
+ folioUuid: dto.folio_uuid,
23
+ toh: dto.toh,
24
+ tibetan: dto.tibetan,
25
+ folioNumber: dto.folio_number,
26
+ volumeNumber: dto.volume_number,
27
+ };
28
+ };
29
+
30
+ export const alignmentsFromDTO = (dtos: AlignmentDTO[]): Alignment[] => {
31
+ return dtos.map(alignmentFromDTO);
32
+ };
@@ -0,0 +1,30 @@
1
+ import type { AnnotationDTO, AnnotationDTOContent } from './annotation-type';
2
+ import {
3
+ type AbbreviationAnnotation,
4
+ type AnnotationExporter,
5
+ type AnnotationTransformer,
6
+ baseAnnotationFromDTO,
7
+ baseAnnotationToDto,
8
+ } from './annotation';
9
+
10
+ export const transformer: AnnotationTransformer = (
11
+ dto,
12
+ ): AbbreviationAnnotation => {
13
+ const baseAnnotation = baseAnnotationFromDTO(dto);
14
+ const abbreviation = baseAnnotation as AbbreviationAnnotation;
15
+ dto.content.forEach((content) => {
16
+ if (content.uuid) {
17
+ abbreviation.abbreviation = content.uuid as string;
18
+ }
19
+ });
20
+ return abbreviation;
21
+ };
22
+
23
+ export const exporter: AnnotationExporter = (annotation): AnnotationDTO => {
24
+ const { abbreviation: uuid } = annotation as AbbreviationAnnotation;
25
+ const dto = baseAnnotationToDto(annotation);
26
+ dto.content.push({
27
+ uuid,
28
+ } as AnnotationDTOContent);
29
+ return dto;
30
+ };