-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHypercertOperationsImpl.ts
More file actions
2711 lines (2486 loc) · 93.7 KB
/
HypercertOperationsImpl.ts
File metadata and controls
2711 lines (2486 loc) · 93.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* HypercertOperationsImpl - High-level hypercert operations.
*
* This module provides the implementation for creating and managing
* hypercerts, including related records like rights, locations,
* contributions, measurements, and evaluations.
*
* @packageDocumentation
*/
import type { Agent } from "@atproto/api";
import { validate } from "@hypercerts-org/lexicon";
import { EventEmitter } from "eventemitter3";
import { NetworkError, ValidationError } from "../errors.js";
import type { LoggerInterface } from "../core/interfaces.js";
import {
HYPERCERT_COLLECTIONS,
type CreateCollectionParams,
type CreateCollectionResult,
type CreateProjectParams,
type CreateProjectResult,
type HypercertClaim,
type HypercertCollection,
type HypercertContributionDetails,
type HypercertContributorInformation,
type HypercertEvaluation,
type HypercertAttachment,
type HypercertLocation,
type CreateLocationParams,
type HypercertMeasurement,
type HypercertRights,
type JsonBlobRef,
type OrgHypercertsDefs,
type StrongRef,
type UpdateCollectionParams,
type UpdateProjectParams,
type CreateMeasurementParams,
type UpdateMeasurementParams,
type CreateAttachmentParams,
} from "../services/hypercerts/types.js";
import type {
BlobOperations,
LocationParams,
CreateHypercertParams,
CreateHypercertResult,
HypercertEvents,
HypercertOperations,
ContributionDetailsParams,
ResolvedContributionDetails,
ContributorIdentityParams,
ResolvedContributorIdentity,
} from "./interfaces.js";
import type { CreateResult, ListParams, PaginatedList, ProgressStep, UpdateResult } from "./types.js";
import { uploadResultToBlobRef } from "./types.js";
import { $Typed } from "@atproto/api";
import { sha256Hash } from "../lib/crypto.js";
/**
* Implementation of high-level hypercert operations.
*
* This class provides a convenient API for creating and managing hypercerts
* with automatic handling of:
*
* - Image upload and blob reference management
* - Rights record creation and linking
* - Location attachment with optional GeoJSON support
* - Contribution tracking
* - Measurement and evaluation records
* - Hypercert collections
*
* The class extends EventEmitter to provide real-time progress notifications
* during complex operations.
*
* @remarks
* This class is typically not instantiated directly. Access it through
* {@link Repository.hypercerts}.
*
* **Record Relationships**:
* - Hypercert → Rights (required, 1:1)
* - Hypercert → Location (optional, 1:many)
* - Hypercert → Contribution (optional, 1:many)
* - Hypercert → Measurement (optional, 1:many)
* - Hypercert → Evaluation (optional, 1:many)
* - Collection → Hypercerts (1:many via claims array)
*
* @example Creating a hypercert with progress tracking
* ```typescript
* repo.hypercerts.on("recordCreated", ({ uri }) => {
* console.log(`Hypercert created: ${uri}`);
* });
*
* const result = await repo.hypercerts.create({
* title: "Climate Impact",
* description: "Reduced emissions by 100 tons",
* workScope: "Climate",
* workTimeframeFrom: "2024-01-01",
* workTimeframeTo: "2024-12-31",
* rights: { name: "CC-BY", type: "license", description: "..." },
* onProgress: (step) => console.log(`${step.name}: ${step.status}`),
* });
* ```
*
* @internal
*/
export class HypercertOperationsImpl extends EventEmitter<HypercertEvents> implements HypercertOperations {
/**
* Creates a new HypercertOperationsImpl.
*
* @param agent - AT Protocol Agent for making API calls
* @param repoDid - DID of the repository to operate on
* @param blobs - Blob operations for uploading images and files
* @param logger - Optional logger for debugging
*
* @internal
*/
constructor(
private agent: Agent,
private repoDid: string,
private blobs: BlobOperations,
private logger?: LoggerInterface,
) {
super();
}
/**
* Emits a progress event to the optional progress handler.
*
* @param onProgress - Progress callback from create params
* @param step - Progress step information
* @internal
*/
private emitProgress(onProgress: ((step: ProgressStep) => void) | undefined, step: ProgressStep): void {
if (onProgress) {
try {
onProgress(step);
} catch (err) {
this.logger?.error(`Error in progress handler: ${err instanceof Error ? err.message : "Unknown"}`);
}
}
}
/**
* Converts a blob upload result to JsonBlobRef format.
*
* @param uploadResult - Result from BlobOperations.upload()
* @returns JsonBlobRef formatted for records
* @internal
*/
private blobToJsonRef(uploadResult: { ref: { $link: string }; mimeType: string; size: number }): JsonBlobRef {
return uploadResultToBlobRef(uploadResult);
}
/**
* Uploads an image blob and returns a blob reference.
*
* @param image - Image blob to upload
* @param onProgress - Optional progress callback
* @returns Promise resolving to blob reference or undefined
* @throws {@link NetworkError} if upload fails
* @internal
*/
private async uploadImageBlob(
image: Blob,
onProgress?: (step: ProgressStep) => void,
): Promise<JsonBlobRef | undefined> {
this.emitProgress(onProgress, { name: "uploadImage", status: "start" });
try {
const uploadResult = await this.blobs.upload(image);
this.emitProgress(onProgress, {
name: "uploadImage",
status: "success",
data: { size: image.size },
});
return this.blobToJsonRef(uploadResult);
} catch (error) {
this.emitProgress(onProgress, { name: "uploadImage", status: "error", error: error as Error });
throw new NetworkError(`Failed to upload image: ${error instanceof Error ? error.message : "Unknown"}`, error);
}
}
/**
* Creates a rights record for a hypercert.
*
* @param rights - Rights data
* @param createdAt - ISO timestamp for creation
* @param onProgress - Optional progress callback
* @returns Promise resolving to rights URI and CID
* @throws {@link ValidationError} if validation fails
* @throws {@link NetworkError} if creation fails
* @internal
*/
private async createRightsRecord(
rights: { name: string; type: string; description: string },
createdAt: string,
onProgress?: (step: ProgressStep) => void,
): Promise<{ uri: string; cid: string }> {
this.emitProgress(onProgress, { name: "createRights", status: "start" });
const rightsRecord: HypercertRights = {
$type: HYPERCERT_COLLECTIONS.RIGHTS,
rightsName: rights.name,
rightsType: rights.type,
rightsDescription: rights.description,
createdAt,
};
const rightsValidation = validate(rightsRecord, HYPERCERT_COLLECTIONS.RIGHTS, "main", false);
if (!rightsValidation.success) {
throw new ValidationError(`Invalid rights record: ${rightsValidation.error?.message}`);
}
const rightsResult = await this.agent.com.atproto.repo.createRecord({
repo: this.repoDid,
collection: HYPERCERT_COLLECTIONS.RIGHTS,
record: rightsRecord as Record<string, unknown>,
});
if (!rightsResult.success) {
throw new NetworkError("Failed to create rights record");
}
const uri = rightsResult.data.uri;
const cid = rightsResult.data.cid;
this.emit("rightsCreated", { uri, cid });
this.emitProgress(onProgress, {
name: "createRights",
status: "success",
data: { uri },
});
return { uri, cid };
}
/**
* Creates the main hypercert record.
*
* @param params - Hypercert creation parameters
* @param rightsUri - URI of the associated rights record
* @param rightsCid - CID of the associated rights record
* @param imageBlobRef - Optional image blob reference
* @param locationRefs - Optional array of strong references to the associated location records
* @param contributorsData - Optional array of contributor data (inline or StrongRef) to embed in the claim
* @param createdAt - ISO timestamp for creation
* @param onProgress - Optional progress callback
* @returns Promise resolving to hypercert URI and CID
* @throws {@link ValidationError} if validation fails
* @throws {@link NetworkError} if creation fails
* @internal
*/
private async createHypercertRecord(
params: CreateHypercertParams,
rightsUri: string,
rightsCid: string,
imageBlobRef: JsonBlobRef | undefined,
locationRefs: Array<{ uri: string; cid: string }> | undefined,
contributorsData:
| Array<{
contributorIdentity: ResolvedContributorIdentity;
contributionWeight?: string;
contributionDetails?: ResolvedContributionDetails;
}>
| undefined,
createdAt: string,
onProgress?: (step: ProgressStep) => void,
): Promise<{ uri: string; cid: string }> {
this.emitProgress(onProgress, { name: "createHypercert", status: "start" });
const hypercertRecord: Record<string, unknown> = {
$type: HYPERCERT_COLLECTIONS.CLAIM,
title: params.title,
shortDescription: params.shortDescription,
description: params.description,
workScope: params.workScope,
startDate: params.startDate,
endDate: params.endDate,
rights: { uri: rightsUri, cid: rightsCid },
createdAt,
};
if (imageBlobRef) {
hypercertRecord.image = imageBlobRef;
}
// Add locations as embedded StrongRefs if provided
if (locationRefs && locationRefs.length > 0) {
hypercertRecord.locations = locationRefs.map((ref) => ({ uri: ref.uri, cid: ref.cid }));
}
if (params.shortDescriptionFacets !== undefined) {
hypercertRecord.shortDescriptionFacets = params.shortDescriptionFacets;
}
if (params.descriptionFacets !== undefined) {
hypercertRecord.descriptionFacets = params.descriptionFacets;
}
// Add contributors if provided (inline role string or StrongRef per lexicon)
if (contributorsData && contributorsData.length > 0) {
hypercertRecord.contributors = contributorsData.map((c) => {
const contributor: Record<string, unknown> = {
contributorIdentity: c.contributorIdentity,
};
if (c.contributionWeight) {
contributor.contributionWeight = c.contributionWeight;
}
if (c.contributionDetails) {
// StrongRef has uri/cid, string is inline role
contributor.contributionDetails = c.contributionDetails;
}
return contributor;
});
}
const hypercertValidation = validate(hypercertRecord, HYPERCERT_COLLECTIONS.CLAIM, "main", false);
if (!hypercertValidation.success) {
throw new ValidationError(`Invalid hypercert record: ${hypercertValidation.error?.message}`);
}
// Generate rKey from stable content hash (idempotency)
// Use NORMALIZED values (already resolved StrongRefs and processed data)
// to ensure JSON-serializability and deterministic hashing.
// Raw params.location can contain non-serializable Blobs (GeoJSON),
// and params.contributions can have arbitrary/inconsistent props.
const hashInput = {
title: params.title,
description: params.description,
shortDescription: params.shortDescription,
workScope: params.workScope,
startDate: params.startDate,
endDate: params.endDate,
// Image: extract CID string from blob ref (stable content hash)
// JsonBlobRef can have ref.$link (upload result) or cid (existing record)
imageRef: imageBlobRef
? "ref" in imageBlobRef && imageBlobRef.ref
? imageBlobRef.ref.$link
: "cid" in imageBlobRef
? imageBlobRef.cid
: undefined
: undefined,
// Rights: canonical object with only known fields
rights: {
name: params.rights.name,
type: params.rights.type,
description: params.rights.description,
},
// Locations: use resolved StrongRefs (uri+cid), not raw params which may be Blob
locationRefs: locationRefs?.map((ref) => ({ uri: ref.uri, cid: ref.cid })),
// Contributors: use already-processed canonical format from processContributors()
contributors: contributorsData,
};
const contentHash = await sha256Hash(hashInput);
const rkey = `hc2:${contentHash}`;
const hypercertResult = await this.agent.com.atproto.repo.createRecord({
repo: this.repoDid,
collection: HYPERCERT_COLLECTIONS.CLAIM,
record: hypercertRecord,
rkey,
});
if (!hypercertResult.success) {
throw new NetworkError("Failed to create hypercert record");
}
const uri = hypercertResult.data.uri;
const cid = hypercertResult.data.cid;
this.emit("recordCreated", { uri, cid });
this.emitProgress(onProgress, {
name: "createHypercert",
status: "success",
data: { uri },
});
return { uri, cid };
}
/**
* Attaches a location to a hypercert with progress tracking.
*
* @param hypercertUri - URI of the hypercert
* @param location - Location data
* @param onProgress - Optional progress callback
* @returns Promise resolving to location URI and CID
* @internal
*/
private async attachLocationWithProgress(
hypercertUri: string,
location: LocationParams,
onProgress?: (step: ProgressStep) => void,
): Promise<CreateResult> {
this.emitProgress(onProgress, { name: "attachLocation", status: "start" });
try {
const locationResult = await this.attachLocation(hypercertUri, location);
this.emitProgress(onProgress, {
name: "attachLocation",
status: "success",
data: { uri: locationResult.uri },
});
return locationResult;
} catch (error) {
this.emitProgress(onProgress, { name: "attachLocation", status: "error", error: error as Error });
this.logger?.warn(`Failed to attach location: ${error instanceof Error ? error.message : "Unknown"}`);
throw error;
}
}
/**
* Creates contribution records with progress tracking.
*
* @param hypercertUri - URI of the hypercert
* @param contributions - Array of contribution data
* @param onProgress - Optional progress callback
* @returns Promise resolving to array of contribution URIs
* @internal
*/
private async createContributionsWithProgress(
hypercertUri: string,
contributions: Array<{
contributors: Array<string | { uri: string; cid: string }>;
role: string;
description?: string;
weight?: string;
}>,
onProgress?: (step: ProgressStep) => void,
): Promise<string[]> {
this.emitProgress(onProgress, { name: "createContributions", status: "start" });
try {
const contributionUris: string[] = [];
for (const contrib of contributions) {
const contribResult = await this.addContribution({
hypercertUri,
contributors: contrib.contributors.filter((c): c is string => typeof c === "string"),
role: contrib.role,
description: contrib.description,
});
contributionUris.push(contribResult.uri);
}
this.emitProgress(onProgress, {
name: "createContributions",
status: "success",
data: { count: contributionUris.length },
});
return contributionUris;
} catch (error) {
this.emitProgress(onProgress, { name: "createContributions", status: "error", error: error as Error });
this.logger?.warn(`Failed to create contributions: ${error instanceof Error ? error.message : "Unknown"}`);
throw error;
}
}
/**
* Creates attachment records and returns their URIs.
*
* @param hypercertUri - URI of the parent hypercert
* @param attachmentItems - Array of attachment items to create
* @param onProgress - Optional progress callback
* @returns Promise resolving to array of attachment URIs
* @internal
*/
private async createAttachmentsWithProgress(
hypercertUri: string,
attachmentItems: Array<Omit<CreateAttachmentParams, "subjects">>,
onProgress?: (step: ProgressStep) => void,
): Promise<string[]> {
this.emitProgress(onProgress, { name: "addAttachment", status: "start" });
try {
const attachmentUris = await Promise.all(
attachmentItems.map((attachment) =>
this.addAttachment({
...attachment,
subjects: hypercertUri,
} as CreateAttachmentParams).then((result) => result.uri),
),
);
this.emitProgress(onProgress, {
name: "addAttachment",
status: "success",
data: { count: attachmentUris.length },
});
return attachmentUris;
} catch (error) {
this.emitProgress(onProgress, { name: "addAttachment", status: "error", error: error as Error });
this.logger?.warn(`Failed to create attachments: ${error instanceof Error ? error.message : "Unknown"}`);
throw error;
}
}
/**
* Creates a new hypercert with all related records.
*
* This method orchestrates the creation of a hypercert and its associated
* records in the correct order:
*
* 1. Upload image (if provided)
* 2. Create rights record
* 3. Create hypercert record (referencing rights)
* 4. Attach location (if provided)
* 5. Create contributions (if provided)
*
* @param params - Creation parameters (see {@link CreateHypercertParams})
* @returns Promise resolving to URIs and CIDs of all created records
* @throws {@link ValidationError} if any record fails validation
* @throws {@link NetworkError} if any API call fails
*
* @remarks
* The operation is not atomic - if a later step fails, earlier records
* will still exist. The returned record reflects the created hypercert,
* including location when attachment succeeds.
*
* **Progress Steps**:
* - `uploadImage`: Image blob upload
* - `createRights`: Rights record creation
* - `createHypercert`: Main hypercert record creation
* - `attachLocation`: Location record creation
* - `createContributions`: Contribution records creation
* - `addAttachment`: Attachment records creation
*
* @example Minimal hypercert
* ```typescript
* const result = await repo.hypercerts.create({
* title: "My Impact",
* description: "Description of impact work",
* shortDescription: "Impact work",
* workScope: "Education",
* startDate: "2024-01-01",
* endDate: "2024-06-30",
* rights: {
* name: "Attribution",
* type: "license",
* description: "CC-BY-4.0",
* },
* });
* ```
*
* @example Full hypercert with all options
* ```typescript
* const result = await repo.hypercerts.create({
* title: "Reforestation Project",
* description: "Planted 10,000 trees...",
* shortDescription: "10K trees planted",
* workScope: "Environment",
* startDate: "2024-01-01",
* endDate: "2024-12-31",
* rights: { name: "Open", type: "impact", description: "..." },
* image: coverImageBlob,
* locations: [{ value: "Amazon, Brazil", name: "Amazon Basin" }],
* contributions: [
* { contributors: ["did:plc:org1"], role: "coordinator" },
* { contributors: ["did:plc:org2"], role: "implementer" },
* ],
* attachments: [{ uri: "https://...", description: "Satellite data" }],
* onProgress: console.log,
* });
* ```
*/
async create(params: CreateHypercertParams): Promise<CreateHypercertResult> {
const createdAt = new Date().toISOString();
const result: CreateHypercertResult = {
hypercertUri: "",
rightsUri: "",
hypercertCid: "",
rightsCid: "",
};
try {
// Step 1: Upload image if provided
const imageBlobRef = params.image ? await this.uploadImageBlob(params.image, params.onProgress) : undefined;
// Step 2: Create location records if provided (must be before hypercert)
// If locations are provided, they must succeed - failing silently would change the rKey on retries
const locationRefs = await this.processLocations(params.locations, params.onProgress);
if (locationRefs && locationRefs.length > 0) {
result.locationUris = locationRefs.map((ref) => ref.uri);
result.locationCids = locationRefs.map((ref) => ref.cid);
}
// Step 3: Create rights record
const { uri: rightsUri, cid: rightsCid } = await this.createRightsRecord(
params.rights,
createdAt,
params.onProgress,
);
result.rightsUri = rightsUri;
result.rightsCid = rightsCid;
// Step 4: Build contributors data for embedding (if provided)
const contributorsData = await this.processContributors(params.contributions, params.onProgress);
// Step 5: Create hypercert record (with embedded locations, rights, and contributors)
const { uri: hypercertUri, cid: hypercertCid } = await this.createHypercertRecord(
params,
rightsUri,
rightsCid,
imageBlobRef,
locationRefs,
contributorsData,
createdAt,
params.onProgress,
);
result.hypercertUri = hypercertUri;
result.hypercertCid = hypercertCid;
// Step 6: Add attachment records if provided
if (params.attachments && params.attachments.length > 0) {
try {
result.attachmentUris = await this.createAttachmentsWithProgress(
hypercertUri,
params.attachments,
params.onProgress,
);
} catch {
// Error already logged and progress emitted
}
}
return result;
} catch (error) {
if (error instanceof ValidationError || error instanceof NetworkError) throw error;
throw new NetworkError(
`Failed to create hypercert: ${error instanceof Error ? error.message : "Unknown"}`,
error,
);
}
}
/**
* Updates an existing hypercert record.
*
* @param params - Update parameters
* @param params.uri - AT-URI of the hypercert to update
* @param params.updates - Partial record with fields to update
* @param params.image - New image blob, `null` to remove, `undefined` to keep existing
* @returns Promise resolving to update result
* @throws {@link ValidationError} if the URI format is invalid or record fails validation
* @throws {@link NetworkError} if the update fails
*
* @remarks
* This is a partial update - only specified fields are changed.
* The `createdAt` and `rights` fields cannot be changed.
*
* @example Update title and description
* ```typescript
* await repo.hypercerts.update({
* uri: "at://did:plc:abc/org.hypercerts.hypercert/xyz",
* updates: {
* title: "Updated Title",
* description: "New description",
* },
* });
* ```
*
* @example Update with new image
* ```typescript
* await repo.hypercerts.update({
* uri: hypercertUri,
* updates: { title: "New Title" },
* image: newImageBlob,
* });
* ```
*
* @example Remove image
* ```typescript
* await repo.hypercerts.update({
* uri: hypercertUri,
* updates: {},
* image: null, // Explicitly remove image
* });
* ```
*/
async update(params: {
uri: string;
updates: Partial<CreateHypercertParams>;
image?: Blob | null;
}): Promise<UpdateResult> {
try {
const uriMatch = params.uri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/);
if (!uriMatch) {
throw new ValidationError(`Invalid URI format: ${params.uri}`);
}
const [, , collection, rkey] = uriMatch;
const existing = await this.agent.com.atproto.repo.getRecord({
repo: this.repoDid,
collection,
rkey,
});
// The existing record comes from ATProto, use it directly
// TypeScript ensures type safety through the HypercertClaim interface
const existingRecord = existing.data.value as HypercertClaim;
const recordForUpdate: Record<string, unknown> = {
...existingRecord,
...params.updates,
createdAt: existingRecord.createdAt,
rights: existingRecord.rights,
};
// Handle image update
delete (recordForUpdate as { image?: unknown }).image;
if (params.image !== undefined) {
if (params.image === null) {
// Remove image
} else {
const uploadResult = await this.blobs.upload(params.image);
recordForUpdate.image = this.blobToJsonRef(uploadResult);
}
} else if (existingRecord.image) {
// Preserve existing image
recordForUpdate.image = existingRecord.image;
}
const validation = validate(recordForUpdate, collection, "main", false);
if (!validation.success) {
throw new ValidationError(`Invalid hypercert record: ${validation.error?.message}`);
}
const result = await this.agent.com.atproto.repo.putRecord({
repo: this.repoDid,
collection,
rkey,
record: recordForUpdate,
});
if (!result.success) {
throw new NetworkError("Failed to update hypercert");
}
this.emit("recordUpdated", { uri: result.data.uri, cid: result.data.cid });
return { uri: result.data.uri, cid: result.data.cid };
} catch (error) {
if (error instanceof ValidationError || error instanceof NetworkError) throw error;
throw new NetworkError(
`Failed to update hypercert: ${error instanceof Error ? error.message : "Unknown"}`,
error,
);
}
}
/**
* Gets a hypercert by its AT-URI.
*
* @param uri - AT-URI of the hypercert (e.g., "at://did:plc:abc/org.hypercerts.hypercert/xyz")
* @returns Promise resolving to hypercert URI, CID, and parsed record
* @throws {@link ValidationError} if the URI format is invalid or record doesn't match schema
* @throws {@link NetworkError} if the record cannot be fetched
*
* @example
* ```typescript
* const { uri, cid, record } = await repo.hypercerts.get(hypercertUri);
* console.log(`${record.title}: ${record.description}`);
* ```
*/
async get(uri: string): Promise<{ uri: string; cid: string; record: HypercertClaim }> {
try {
const uriMatch = uri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/);
if (!uriMatch) {
throw new ValidationError(`Invalid URI format: ${uri}`);
}
const [, , collection, rkey] = uriMatch;
const result = await this.agent.com.atproto.repo.getRecord({
repo: this.repoDid,
collection,
rkey,
});
if (!result.success) {
throw new NetworkError("Failed to get hypercert");
}
return {
uri: result.data.uri,
cid: result.data.cid ?? "",
record: result.data.value as HypercertClaim,
};
} catch (error) {
if (error instanceof ValidationError || error instanceof NetworkError) throw error;
throw new NetworkError(`Failed to get hypercert: ${error instanceof Error ? error.message : "Unknown"}`, error);
}
}
/**
* Lists hypercerts in the repository with pagination.
*
* @param params - Optional pagination parameters
* @returns Promise resolving to paginated list of hypercerts
* @throws {@link NetworkError} if the list operation fails
*
* @example
* ```typescript
* // Get first page
* const { records, cursor } = await repo.hypercerts.list({ limit: 20 });
*
* // Get next page
* if (cursor) {
* const nextPage = await repo.hypercerts.list({ limit: 20, cursor });
* }
* ```
*/
async list(params?: ListParams): Promise<PaginatedList<{ uri: string; cid: string; record: HypercertClaim }>> {
try {
const result = await this.agent.com.atproto.repo.listRecords({
repo: this.repoDid,
collection: HYPERCERT_COLLECTIONS.CLAIM,
limit: params?.limit,
cursor: params?.cursor,
});
if (!result.success) {
throw new NetworkError("Failed to list hypercerts");
}
return {
records:
result.data.records?.map((r) => ({
uri: r.uri,
cid: r.cid,
record: r.value as HypercertClaim,
})) || [],
cursor: result.data.cursor ?? undefined,
};
} catch (error) {
if (error instanceof NetworkError) throw error;
throw new NetworkError(`Failed to list hypercerts: ${error instanceof Error ? error.message : "Unknown"}`, error);
}
}
/**
* Deletes a hypercert record.
*
* @param uri - AT-URI of the hypercert to delete
* @throws {@link ValidationError} if the URI format is invalid
* @throws {@link NetworkError} if the deletion fails
*
* @remarks
* This only deletes the hypercert record itself. Related records
* (rights, locations, contributions) are not automatically deleted.
*
* @example
* ```typescript
* await repo.hypercerts.delete(hypercertUri);
* ```
*/
async delete(uri: string): Promise<void> {
try {
const uriMatch = uri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/);
if (!uriMatch) {
throw new ValidationError(`Invalid URI format: ${uri}`);
}
const [, , collection, rkey] = uriMatch;
const result = await this.agent.com.atproto.repo.deleteRecord({
repo: this.repoDid,
collection,
rkey,
});
if (!result.success) {
throw new NetworkError("Failed to delete hypercert");
}
} catch (error) {
if (error instanceof ValidationError || error instanceof NetworkError) throw error;
throw new NetworkError(
`Failed to delete hypercert: ${error instanceof Error ? error.message : "Unknown"}`,
error,
);
}
}
/**
* Attaches a location to an existing hypercert.
*
* @param hypercertUri - AT-URI of the hypercert to attach location to
* @param location - Location data
* @param location.value - Location value (address, coordinates, or description)
* @param location.name - Optional human-readable name
* @param location.description - Optional description
* @param location.srs - Spatial Reference System (e.g., "EPSG:4326")
* @param location.geojson - Optional GeoJSON blob for precise boundaries
* @returns Promise resolving to location record URI and CID
* @throws {@link ValidationError} if validation fails
* @throws {@link NetworkError} if the operation fails
*
* @example Simple location
* ```typescript
* await repo.hypercerts.attachLocation(hypercertUri, {
* value: "San Francisco, CA",
* name: "SF Bay Area",
* srs: "EPSG:4326",
* });
* ```
*
* @example Location with GeoJSON
* ```typescript
* const geojsonBlob = new Blob([JSON.stringify(geojson)], {
* type: "application/geo+json"
* });
*
* await repo.hypercerts.attachLocation(hypercertUri, {
* value: "Custom Region",
* srs: "EPSG:4326",
* geojson: geojsonBlob,
* });
* ```
*/
async attachLocation(hypercertUri: string, location: LocationParams): Promise<CreateResult> {
try {
// Get existing hypercert to preserve current locations
const existing = await this.get(hypercertUri);
const resolvedLocation = await this.resolveLocation(location);
// Build new locations array: existing + new location
const existingLocations = existing.record.locations || [];
const newLocations = [
...existingLocations,
{
$type: "com.atproto.repo.strongRef",
uri: resolvedLocation.uri,
cid: resolvedLocation.cid,
} as StrongRef,
];
await this.update({
uri: hypercertUri,
updates: {
locations: newLocations,
},
});
this.emit("locationAttached", {
uri: resolvedLocation.uri,
cid: resolvedLocation.cid,
hypercertUri,
});
return { uri: resolvedLocation.uri, cid: resolvedLocation.cid };
} catch (error) {
if (error instanceof ValidationError || error instanceof NetworkError) throw error;
throw new NetworkError(`Failed to attach location: ${error instanceof Error ? error.message : "Unknown"}`, error);
}
}
/**
* Generic helper to resolve string | Blob into a URI or blob reference.
*
* @param content - Either a URI string or a Blob to upload
* @param fallbackMimeType - MIME type to use if Blob.type is empty
* @returns Promise resolving to either a URI ref or blob ref
* @internal
*/
private async resolveUriOrBlob(content: string | Blob, _fallbackMimeType: string) {
if (typeof content === "string") {
const uriRef = {
$type: "org.hypercerts.defs#uri",
uri: content,
} satisfies $Typed<OrgHypercertsDefs.Uri>;
return uriRef;
}
const uploadResult = await this.blobs.upload(content);
return {
$type: "org.hypercerts.defs#smallBlob" as const,
blob: this.blobToJsonRef(uploadResult),
};
}
private async resolveCollectionImageInput(input: string | Blob): Promise<NonNullable<HypercertCollection["avatar"]>>;
private async resolveCollectionImageInput(
input: string | Blob,
isBanner: true,
): Promise<NonNullable<HypercertCollection["banner"]>>;
private async resolveCollectionImageInput(input: string | Blob, isBanner: boolean = false) {
if (typeof input === "string") {
return { $type: "org.hypercerts.defs#uri" as const, uri: input };
}
const uploadResult = await this.blobs.upload(input);
const blobRef = this.blobToJsonRef(uploadResult);
if (isBanner) {
return { $type: "org.hypercerts.defs#largeImage" as const, image: blobRef };
}
return { $type: "org.hypercerts.defs#smallImage" as const, image: blobRef };
}
/**
* Resolves a location value to the appropriate lexicon format.
*
* Handles three input formats:
* - **string** - Wrapped in `{ $type: "org.hypercerts.defs#uri", uri: ... }`
* This supports both free-form text ("New York, NY") and URLs
* - **Blob** - Uploaded and wrapped in `{ $type: "org.hypercerts.defs#smallBlob", blob: ... }`
* - **Structured object** - Passed through unchanged (already in lexicon format)
*
* @param location - Location value in any supported format
* @returns Promise resolving to lexicon-compliant location value
* @internal
*/
private async resolveLocationValue(location: string | Blob | HypercertLocation["location"]) {
if (typeof location === "string" || location instanceof Blob) {
return this.resolveUriOrBlob(location, "application/geo+json");