-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcard-api.gts
3087 lines (2874 loc) · 88.2 KB
/
card-api.gts
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
import Modifier from 'ember-modifier';
import { action } from '@ember/object';
import GlimmerComponent from '@glimmer/component';
import { flatMap, merge, isEqual } from 'lodash';
import { TrackedWeakMap } from 'tracked-built-ins';
import { WatchedArray } from './watched-array';
import { BoxelInput, FieldContainer } from '@cardstack/boxel-ui/components';
import { cn, eq, pick } from '@cardstack/boxel-ui/helpers';
import { on } from '@ember/modifier';
import { startCase } from 'lodash';
import { getBoxComponent, type BoxComponent } from './field-component';
import { getContainsManyComponent } from './contains-many-component';
import { getLinksToEditor } from './links-to-editor';
import { getLinksToManyComponent } from './links-to-many-component';
import {
SupportedMimeType,
Deferred,
isCardResource,
Loader,
isSingleCardDocument,
isRelationship,
isNotLoadedError,
isNotReadyError,
CardError,
NotLoaded,
NotReady,
getField,
isField,
primitive,
identifyCard,
isCardDef,
isCardInstance as _isCardInstance,
loadCard,
humanReadable,
maybeURL,
maybeRelativeURL,
moduleFrom,
getCard,
trackCard,
type Meta,
type CardFields,
type Relationship,
type LooseCardResource,
type LooseSingleCardDocument,
type CardDocument,
type CardResource,
type Actions,
type RealmInfo,
} from '@cardstack/runtime-common';
import type { ComponentLike } from '@glint/template';
import { initSharedState } from './shared-state';
export { primitive, isField, type BoxComponent };
export const serialize = Symbol.for('cardstack-serialize');
export const deserialize = Symbol.for('cardstack-deserialize');
export const useIndexBasedKey = Symbol.for('cardstack-use-index-based-key');
export const fieldDecorator = Symbol.for('cardstack-field-decorator');
export const fieldType = Symbol.for('cardstack-field-type');
export const queryableValue = Symbol.for('cardstack-queryable-value');
export const relativeTo = Symbol.for('cardstack-relative-to');
export const realmInfo = Symbol.for('cardstack-realm-info');
export const realmURL = Symbol.for('cardstack-realm-url');
// intentionally not exporting this so that the outside world
// cannot mark a card as being saved
const isSavedInstance = Symbol.for('cardstack-is-saved-instance');
export type BaseInstanceType<T extends BaseDefConstructor> = T extends {
[primitive]: infer P;
}
? P
: InstanceType<T>;
export type PartialBaseInstanceType<T extends BaseDefConstructor> = T extends {
[primitive]: infer P;
}
? P | null
: Partial<InstanceType<T>>;
export type FieldsTypeFor<T extends BaseDef> = {
[Field in keyof T]: BoxComponent &
(T[Field] extends ArrayLike<unknown>
? BoxComponent[]
: T[Field] extends BaseDef
? FieldsTypeFor<T[Field]>
: unknown);
};
export const formats: Format[] = ['isolated', 'embedded', 'edit', 'atom'];
export type Format = 'isolated' | 'embedded' | 'edit' | 'atom';
export type FieldType = 'contains' | 'containsMany' | 'linksTo' | 'linksToMany';
type Setter = (value: any) => void;
interface Options {
computeVia?: string | (() => unknown);
// there exists cards that we only ever run in the host without
// the isolated renderer (RoomField), which means that we cannot
// use the rendering mechanism to tell if a card is used or not,
// in which case we need to tell the runtime that a card is
// explictly being used.
isUsed?: true;
}
interface NotLoadedValue {
type: 'not-loaded';
reference: string;
}
export interface CardContext {
actions?: Actions;
cardComponentModifier?: typeof Modifier<{
Args: {
Named: {
card: CardDef;
format: Format | 'data';
fieldType: FieldType | undefined;
fieldName: string | undefined;
};
};
}>;
renderedIn?: Component<any>;
}
function isNotLoadedValue(val: any): val is NotLoadedValue {
if (!val || typeof val !== 'object') {
return false;
}
if (!('type' in val) || !('reference' in val)) {
return false;
}
let { type, reference } = val;
if (typeof type !== 'string' || typeof reference !== 'string') {
return false;
}
return type === 'not-loaded';
}
interface NotReadyValue {
type: 'not-ready';
instance: BaseDef;
fieldName: string;
}
function isNotReadyValue(value: any): value is NotReadyValue {
if (value && typeof value === 'object') {
return (
'type' in value &&
value.type === 'not-ready' &&
'instance' in value &&
isCardOrField(value.instance) &&
'fieldName' in value &&
typeof value.fieldName === 'string'
);
} else {
return false;
}
}
interface StaleValue {
type: 'stale';
staleValue: any;
}
type CardChangeSubscriber = (
instance: BaseDef,
fieldName: string,
fieldValue: any,
) => void;
function isStaleValue(value: any): value is StaleValue {
if (value && typeof value === 'object') {
return 'type' in value && value.type === 'stale' && 'staleValue' in value;
} else {
return false;
}
}
const deserializedData = initSharedState(
'deserializedData',
() => new WeakMap<BaseDef, Map<string, any>>(),
);
const recomputePromises = initSharedState(
'recomputePromises',
() => new WeakMap<BaseDef, Promise<any>>(),
);
const identityContexts = initSharedState(
'identityContexts',
() => new WeakMap<BaseDef, IdentityContext>(),
);
const subscribers = initSharedState(
'subscribers',
() => new WeakMap<BaseDef, Set<CardChangeSubscriber>>(),
);
// our place for notifying Glimmer when a card is ready to re-render (which will
// involve rerunning async computed fields)
const cardTracking = initSharedState(
'cardTracking',
() => new TrackedWeakMap<object, any>(),
);
const isBaseInstance = Symbol.for('isBaseInstance');
class Logger {
private promises: Promise<any>[] = [];
log(promise: Promise<any>) {
this.promises.push(promise);
// make an effort to resolve the promise at the time it is logged
(async () => {
try {
await promise;
} catch (e: any) {
console.error(`encountered error performing recompute on card`, e);
}
})();
}
async flush() {
let results = await Promise.allSettled(this.promises);
for (let result of results) {
if (result.status === 'rejected') {
console.error(`Promise rejected`, result.reason);
if (result.reason instanceof Error) {
console.error(result.reason.stack);
}
}
}
}
}
let logger = new Logger();
export async function flushLogs() {
await logger.flush();
}
export class IdentityContext {
readonly identities = new Map<string, CardDef>();
}
type JSONAPIResource =
| {
attributes: Record<string, any>;
relationships?: Record<string, Relationship>;
meta?: Record<string, any>;
}
| {
attributes?: Record<string, any>;
relationships: Record<string, Relationship>;
meta?: Record<string, any>;
};
export interface JSONAPISingleResourceDocument {
data: Partial<JSONAPIResource> & { id?: string; type: string };
included?: (Partial<JSONAPIResource> & { id: string; type: string })[];
}
export interface Field<
CardT extends BaseDefConstructor = BaseDefConstructor,
SearchT = any,
> {
card: CardT;
name: string;
fieldType: FieldType;
computeVia: undefined | string | (() => unknown);
// there exists cards that we only ever run in the host without
// the isolated renderer (RoomField), which means that we cannot
// use the rendering mechanism to tell if a card is used or not,
// in which case we need to tell the runtime that a card is
// explictly being used.
isUsed?: undefined | true;
serialize(
value: any,
doc: JSONAPISingleResourceDocument,
visited: Set<string>,
opts?: SerializeOpts,
): JSONAPIResource;
deserialize(
value: any,
doc: LooseSingleCardDocument | CardDocument,
relationships: JSONAPIResource['relationships'] | undefined,
fieldMeta: CardFields[string] | undefined,
identityContext: IdentityContext | undefined,
instancePromise: Promise<BaseDef>,
loadedValue: any,
relativeTo: URL | undefined,
): Promise<any>;
emptyValue(instance: BaseDef): any;
validate(instance: BaseDef, value: any): void;
component(
model: Box<BaseDef>,
defaultFormat: Format,
context?: CardContext,
): BoxComponent;
getter(instance: BaseDef): BaseInstanceType<CardT>;
queryableValue(value: any, stack: BaseDef[]): SearchT;
queryMatcher(
innerMatcher: (innerValue: any) => boolean | null,
): (value: SearchT) => boolean | null;
handleNotLoadedError(
instance: BaseInstanceType<CardT>,
e: NotLoaded,
opts?: RecomputeOptions,
): Promise<
BaseInstanceType<CardT> | BaseInstanceType<CardT>[] | undefined | void
>;
}
function callSerializeHook(
card: typeof BaseDef,
value: any,
doc: JSONAPISingleResourceDocument,
visited: Set<string> = new Set(),
opts?: SerializeOpts,
) {
if (value != null) {
return card[serialize](value, doc, visited, opts);
} else {
return null;
}
}
function cardTypeFor(
field: Field<typeof BaseDef>,
boxedElement: Box<BaseDef>,
): typeof BaseDef {
if (primitive in field.card) {
return field.card;
}
return Reflect.getPrototypeOf(boxedElement.value)!
.constructor as typeof BaseDef;
}
function resourceFrom(
doc: CardDocument | undefined,
resourceId: string | undefined,
): LooseCardResource | undefined {
if (doc == null) {
return undefined;
}
let data: CardResource[];
if (isSingleCardDocument(doc)) {
if (resourceId == null) {
return doc.data;
}
data = [doc.data];
} else {
data = doc.data;
}
let res = [...data, ...(doc.included ?? [])].find(
(resource) => resource.id === resourceId,
);
return res;
}
function getter<CardT extends BaseDefConstructor>(
instance: BaseDef,
field: Field<CardT>,
): BaseInstanceType<CardT> {
let deserialized = getDataBucket(instance);
// this establishes that our field should rerender when cardTracking for this card changes
cardTracking.get(instance);
if (field.computeVia) {
let value = deserialized.get(field.name);
if (isStaleValue(value)) {
value = value.staleValue;
} else if (
!deserialized.has(field.name) &&
typeof field.computeVia === 'function' &&
field.computeVia.constructor.name !== 'AsyncFunction'
) {
value = field.computeVia.bind(instance)();
deserialized.set(field.name, value);
} else if (
!deserialized.has(field.name) &&
(typeof field.computeVia === 'string' ||
typeof field.computeVia === 'function')
) {
throw new NotReady(instance, field.name, field.computeVia);
}
return value;
} else {
if (deserialized.has(field.name)) {
return deserialized.get(field.name);
}
let value = field.emptyValue(instance);
deserialized.set(field.name, value);
return value;
}
}
class ContainsMany<FieldT extends FieldDefConstructor>
implements Field<FieldT, any[]>
{
readonly fieldType = 'containsMany';
constructor(
private cardThunk: () => FieldT,
readonly computeVia: undefined | string | (() => unknown),
readonly name: string,
readonly isUsed: undefined | true,
) {}
get card(): FieldT {
return this.cardThunk();
}
getter(instance: BaseDef): BaseInstanceType<FieldT> {
return getter(instance, this);
}
queryableValue(instances: any[] | null, stack: BaseDef[]): any[] {
if (instances == null) {
return [];
}
// Need to replace the WatchedArray proxy with an actual array because the
// WatchedArray proxy is not structuredClone-able, and hence cannot be
// communicated over the postMessage boundary between worker and DOM.
// TODO: can this be simplified since we don't have the worker anymore?
return [...instances].map((instance) => {
return this.card[queryableValue](instance, stack);
});
}
queryMatcher(
innerMatcher: (innerValue: any) => boolean | null,
): (value: any[]) => boolean | null {
return (value) => {
if (value.length === 0) {
return innerMatcher(null);
}
return value.some((innerValue) => {
return innerMatcher(innerValue);
});
};
}
serialize(
values: BaseInstanceType<FieldT>[],
doc: JSONAPISingleResourceDocument,
_visited: Set<string>,
opts?: SerializeOpts,
): JSONAPIResource {
if (primitive in this.card) {
return {
attributes: {
[this.name]: values.map((value) =>
callSerializeHook(this.card, value, doc, undefined, opts),
),
},
};
} else {
let relationships: Record<string, Relationship> = {};
let serialized = values.map((value, index) => {
let resource: JSONAPISingleResourceDocument['data'] = callSerializeHook(
this.card,
value,
doc,
undefined,
opts,
);
if (resource.relationships) {
for (let [fieldName, relationship] of Object.entries(
resource.relationships as Record<string, Relationship>,
)) {
relationships[`${this.name}.${index}.${fieldName}`] = relationship; // warning side-effect
}
}
if (this.card === Reflect.getPrototypeOf(value)!.constructor) {
// when our implementation matches the default we don't need to include
// meta.adoptsFrom
delete resource.meta?.adoptsFrom;
}
if (resource.meta && Object.keys(resource.meta).length === 0) {
delete resource.meta;
}
return resource;
});
let result: JSONAPIResource = {
attributes: {
[this.name]: serialized.map((resource) => resource.attributes),
},
};
if (Object.keys(relationships).length > 0) {
result.relationships = relationships;
}
if (serialized.some((resource) => resource.meta)) {
result.meta = {
fields: {
[this.name]: serialized.map((resource) => resource.meta ?? {}),
},
};
}
return result;
}
}
async deserialize(
value: any[],
doc: CardDocument,
relationships: JSONAPIResource['relationships'] | undefined,
fieldMeta: CardFields[string] | undefined,
_identityContext: undefined,
instancePromise: Promise<BaseDef>,
_loadedValue: any,
relativeTo: URL | undefined,
): Promise<BaseInstanceType<FieldT>[]> {
if (!Array.isArray(value)) {
throw new Error(`Expected array for field value ${this.name}`);
}
if (fieldMeta && !Array.isArray(fieldMeta)) {
throw new Error(
`fieldMeta for contains-many field '${
this.name
}' is not an array: ${JSON.stringify(fieldMeta, null, 2)}`,
);
}
let metas: Partial<Meta>[] = fieldMeta ?? [];
return new WatchedArray(
(arrayValue) =>
instancePromise.then((instance) => {
notifySubscribers(instance, field.name, arrayValue);
logger.log(recompute(instance));
}),
await Promise.all(
value.map(async (entry, index) => {
if (primitive in this.card) {
return this.card[deserialize](entry, relativeTo, doc);
} else {
let meta = metas[index];
let resource: LooseCardResource = {
attributes: entry,
meta: makeMetaForField(meta, this.name, this.card),
};
if (relationships) {
resource.relationships = Object.fromEntries(
Object.entries(relationships)
.filter(([fieldName]) =>
fieldName.startsWith(`${this.name}.`),
)
.map(([fieldName, relationship]) => {
let relName = `${this.name}.${index}`;
return [
fieldName.startsWith(`${relName}.`)
? fieldName.substring(relName.length + 1)
: fieldName,
relationship,
];
}),
);
}
return (
await cardClassFromResource(resource, this.card, relativeTo)
)[deserialize](resource, relativeTo, doc);
}
}),
),
);
}
emptyValue(instance: BaseDef) {
return new WatchedArray((value) => {
notifySubscribers(instance, this.name, value);
logger.log(recompute(instance));
});
}
validate(instance: BaseDef, value: any) {
if (value && !Array.isArray(value)) {
throw new Error(`Expected array for field value ${this.name}`);
}
return new WatchedArray((value) => {
notifySubscribers(instance, this.name, value);
logger.log(recompute(instance));
}, value);
}
async handleNotLoadedError<T extends BaseDef>(instance: T, _e: NotLoaded) {
throw new Error(
`cannot load missing field for non-linksTo or non-linksToMany field ${instance.constructor.name}.${this.name}`,
);
}
component(model: Box<BaseDef>, format: Format): BoxComponent {
let fieldName = this.name as keyof BaseDef;
let arrayField = model.field(
fieldName,
useIndexBasedKey in this.card,
) as unknown as Box<BaseDef[]>;
let renderFormat: Format | undefined = undefined;
if (
format === 'edit' &&
'isFieldDef' in model.value.constructor &&
model.value.constructor.isFieldDef
) {
renderFormat = 'atom';
}
return getContainsManyComponent({
model,
arrayField,
field: this,
format: renderFormat ?? format,
cardTypeFor,
});
}
}
class Contains<CardT extends FieldDefConstructor> implements Field<CardT, any> {
readonly fieldType = 'contains';
constructor(
private cardThunk: () => CardT,
readonly computeVia: undefined | string | (() => unknown),
readonly name: string,
readonly isUsed: undefined | true,
) {}
get card(): CardT {
return this.cardThunk();
}
getter(instance: BaseDef): BaseInstanceType<CardT> {
return getter(instance, this);
}
queryableValue(instance: any, stack: BaseDef[]): any {
if (primitive in this.card) {
let result = this.card[queryableValue](instance, stack);
assertScalar(result, this.card);
return result;
}
if (instance == null) {
return null;
}
return this.card[queryableValue](instance, stack);
}
queryMatcher(
innerMatcher: (innerValue: any) => boolean | null,
): (value: any) => boolean | null {
return (value) => innerMatcher(value);
}
serialize(
value: InstanceType<CardT>,
doc: JSONAPISingleResourceDocument,
): JSONAPIResource {
let serialized: JSONAPISingleResourceDocument['data'] & {
meta: Record<string, any>;
} = callSerializeHook(this.card, value, doc);
if (primitive in this.card) {
return { attributes: { [this.name]: serialized } };
} else {
let resource: JSONAPIResource = {
attributes: {
[this.name]: serialized?.attributes,
},
};
if (serialized == null) {
return resource;
}
if (serialized.relationships) {
resource.relationships = {};
for (let [fieldName, relationship] of Object.entries(
serialized.relationships as Record<string, Relationship>,
)) {
resource.relationships[`${this.name}.${fieldName}`] = relationship;
}
}
if (this.card === Reflect.getPrototypeOf(value)!.constructor) {
// when our implementation matches the default we don't need to include
// meta.adoptsFrom
delete serialized.meta.adoptsFrom;
}
if (Object.keys(serialized.meta).length > 0) {
resource.meta = {
fields: { [this.name]: serialized.meta },
};
}
return resource;
}
}
async deserialize(
value: any,
doc: CardDocument,
relationships: JSONAPIResource['relationships'] | undefined,
fieldMeta: CardFields[string] | undefined,
_identityContext: undefined,
_instancePromise: Promise<BaseDef>,
_loadedValue: any,
relativeTo: URL | undefined,
): Promise<BaseInstanceType<CardT>> {
if (primitive in this.card) {
return this.card[deserialize](value, relativeTo, doc);
}
if (fieldMeta && Array.isArray(fieldMeta)) {
throw new Error(
`fieldMeta for contains field '${
this.name
}' is an array: ${JSON.stringify(fieldMeta, null, 2)}`,
);
}
let meta: Partial<Meta> | undefined = fieldMeta;
let resource: LooseCardResource = {
attributes: value,
meta: makeMetaForField(meta, this.name, this.card),
};
if (relationships) {
resource.relationships = Object.fromEntries(
Object.entries(relationships)
.filter(([fieldName]) => fieldName.startsWith(`${this.name}.`))
.map(([fieldName, relationship]) => [
fieldName.startsWith(`${this.name}.`)
? fieldName.substring(this.name.length + 1)
: fieldName,
relationship,
]),
);
}
return (await cardClassFromResource(resource, this.card, relativeTo))[
deserialize
](resource, relativeTo, doc);
}
emptyValue(_instance: BaseDef) {
if (primitive in this.card) {
return undefined;
} else {
return new this.card();
}
}
validate(_instance: BaseDef, value: any) {
if (primitive in this.card) {
// todo: primitives could implement a validation symbol
} else {
if (value != null && !(value instanceof this.card)) {
throw new Error(
`tried set ${value} as field ${this.name} but it is not an instance of ${this.card.name}`,
);
}
}
return value;
}
async handleNotLoadedError<T extends BaseDef>(instance: T, _e: NotLoaded) {
throw new Error(
`cannot load missing field for non-linksTo or non-linksToMany field ${instance.constructor.name}.${this.name}`,
);
}
component(
model: Box<BaseDef>,
format: Format,
context?: CardContext,
): BoxComponent {
return fieldComponent(this, model, format, context);
}
}
class LinksTo<CardT extends CardDefConstructor> implements Field<CardT> {
readonly fieldType = 'linksTo';
constructor(
private cardThunk: () => CardT,
readonly computeVia: undefined | string | (() => unknown),
readonly name: string,
readonly isUsed: undefined | true,
) {}
get card(): CardT {
return this.cardThunk();
}
getter(instance: CardDef): BaseInstanceType<CardT> {
let deserialized = getDataBucket(instance);
// this establishes that our field should rerender when cardTracking for this card changes
cardTracking.get(instance);
let maybeNotLoaded = deserialized.get(this.name);
if (isNotLoadedValue(maybeNotLoaded)) {
throw new NotLoaded(instance, maybeNotLoaded.reference, this.name);
}
return getter(instance, this);
}
queryableValue(instance: any, stack: CardDef[]): any {
if (primitive in this.card) {
throw new Error(
`the linksTo field '${this.name}' contains a primitive card '${this.card.name}'`,
);
}
if (instance == null) {
return null;
}
return this.card[queryableValue](instance, stack);
}
queryMatcher(
innerMatcher: (innerValue: any) => boolean | null,
): (value: any) => boolean | null {
return (value) => innerMatcher(value);
}
serialize(
value: InstanceType<CardT>,
doc: JSONAPISingleResourceDocument,
visited: Set<string>,
opts?: SerializeOpts,
) {
if (isNotLoadedValue(value)) {
return {
relationships: {
[this.name]: {
links: {
self: makeRelativeURL(value.reference, opts),
},
},
},
};
}
if (value == null) {
return {
relationships: {
[this.name]: {
links: { self: null },
},
},
};
}
if (visited.has(value.id)) {
return {
relationships: {
[this.name]: {
links: {
self: makeRelativeURL(value.id, opts),
},
data: { type: 'card', id: value.id },
},
},
};
}
visited.add(value.id);
let serialized = callSerializeHook(this.card, value, doc, visited, opts) as
| (JSONAPIResource & { id: string; type: string })
| null;
if (serialized) {
if (!value[isSavedInstance]) {
throw new Error(
`the linksTo field '${this.name}' cannot be serialized with an unsaved card`,
);
}
let resource: JSONAPIResource = {
relationships: {
[this.name]: {
links: {
self: makeRelativeURL(value.id, opts),
},
// we also write out the data form of the relationship
// which correlates to the included resource
data: { type: 'card', id: value.id },
},
},
};
if (
!(doc.included ?? []).find((r) => r.id === value.id) &&
doc.data.id !== value.id
) {
doc.included = doc.included ?? [];
doc.included.push(serialized);
}
return resource;
}
return {
relationships: {
[this.name]: {
links: { self: null },
},
},
};
}
async deserialize(
value: any,
doc: CardDocument,
_relationships: undefined,
_fieldMeta: undefined,
identityContext: IdentityContext,
_instancePromise: Promise<CardDef>,
loadedValue: any,
relativeTo: URL | undefined,
): Promise<BaseInstanceType<CardT> | null | NotLoadedValue> {
if (!isRelationship(value)) {
throw new Error(
`linkTo field '${
this.name
}' cannot deserialize non-relationship value ${JSON.stringify(value)}`,
);
}
if (value?.links?.self == null) {
return null;
}
let loader = Loader.getLoaderFor(this.card)!;
let cardResource = getCard(new URL(value.links.self, relativeTo), {
cachedOnly: true,
loader,
});
await cardResource.loaded;
let cachedInstance =
cardResource.card ?? identityContext.identities.get(value.links.self);
if (cachedInstance) {
cachedInstance[isSavedInstance] = true;
return cachedInstance as BaseInstanceType<CardT>;
}
let resourceId = new URL(value.links.self, relativeTo).href;
let resource = resourceFrom(doc, resourceId);
if (!resource) {
if (loadedValue !== undefined) {
return loadedValue;
}
return {
type: 'not-loaded',
reference: value.links.self,
};
}
let clazz = await cardClassFromResource(resource, this.card, relativeTo);
let deserialized = await clazz[deserialize](
resource,
relativeTo,
doc,
identityContext,
);
deserialized[isSavedInstance] = true;
deserialized = trackCard(
loader,
deserialized,
deserialized[realmURL]!,
) as BaseInstanceType<CardT>;
return deserialized;
}
emptyValue(_instance: CardDef) {
return null;
}
validate(_instance: CardDef, value: any) {
// we can't actually place this in the constructor since that would break cards whose field type is themselves
// so the next opportunity we have to test this scenario is during field assignment
if (primitive in this.card) {
throw new Error(
`the linksTo field '${this.name}' contains a primitive card '${this.card.name}'`,
);
}
if (value) {
if (isNotLoadedValue(value)) {
return value;
}
if (!(value instanceof this.card)) {
throw new Error(
`tried set ${value} as field '${this.name}' but it is not an instance of ${this.card.name}`,
);
}
}
return value;
}
async handleNotLoadedError(
instance: BaseInstanceType<CardT>,
e: NotLoaded,
opts?: RecomputeOptions,
): Promise<BaseInstanceType<CardT> | undefined> {
let deserialized = getDataBucket(instance as BaseDef);
let identityContext =
identityContexts.get(instance as BaseDef) ?? new IdentityContext();
// taking advantage of the identityMap regardless of whether loadFields is set
let fieldValue = identityContext.identities.get(e.reference as string);
if (fieldValue !== undefined) {
deserialized.set(this.name, fieldValue);
return fieldValue as BaseInstanceType<CardT>;
}
if (opts?.loadFields) {
fieldValue = await this.loadMissingField(
instance,
e,
identityContext,
instance[relativeTo],
);
deserialized.set(this.name, fieldValue);
return fieldValue as BaseInstanceType<CardT>;
}
return;
}