/
causal.ts
3758 lines (3245 loc) · 102 KB
/
causal.ts
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
// This is a FeatureDL automatically generated file. DO NOT DIRECTLY EDIT, your changes will not persist.
import fetch from "cross-fetch";
class FeatureBase {
// featureName FeatureBasewill always be set
// we don't want to set them in the constructor
// This is to save on lines of geenrated code
// It is set when the impresson is created
featureName?: string;
readonly _: {
impressionId?: string;
impression?: Impression<FeatureNames>;
} = {};
}
// TSBase - start
//#region parameterized
/* eslint-disable */
export interface ImpressionTime {
impressionId: string;
impressionTime: number;
}
/**
* Wraps a rating box that we can put on various product pages
* to collect ratings from our users
*/
export class RatingBox extends FeatureBase {
/**
* The product that we are collecting ratings for
*/
readonly product: string = "";
/**
* The text next to the stars that prompts the visitor to rate the product
*
* Control: "Rate this product!"
*/
readonly callToAction: string = "Rate this product!";
/**
* The button text for the user submit a review.
*
* Control: "Send Review"
*/
readonly actionButton: string = "Send Review";
/**
* Occurs each time a rating is collected
*/
signalRating( { stars }
: { stars : number } ) : void {
signalInstance(this, "Rating", arguments[0]);
}
/**
* Occurs each time a rating is collected
*/
static signalRating( sessionKeys: SessionKeys | Session, impressionId : string, { stars }
: { stars : number } ) : void
{
signalStatic("RatingBox", "Rating", [...arguments]);
}
}
/**
* An empty feature to use only as a kill switch
*/
export class ProductInfo extends FeatureBase {
}
/**
* Another feature just for demonstration purposes
*/
export class Feature2 extends FeatureBase {
/**
* Example args
*/
readonly exampleArg: string = "";
/**
* Example output
*
* Control: "Example output"
*/
readonly exampleOutput: string = "Example output";
/**
* Example event
*/
signalExampleEvent( { data }
: { data : string } ) : void {
signalInstance(this, "ExampleEvent", arguments[0]);
}
/**
* Example event
*/
static signalExampleEvent( sessionKeys: SessionKeys | Session, impressionId : string, { data }
: { data : string } ) : void
{
signalStatic("Feature2", "ExampleEvent", [...arguments]);
}
}
/* eslint-enable */
/** @deprecated */
export const allFeatureTypes = {
RatingBox,
ProductInfo,
Feature2,
};
/**
* The arguments defined in the args section of the FDL schema
*/
export type SessionArgs = {
deviceId: string;
};
/* eslint-disable */
class SessionEvents {
readonly _: { sessionKeys: SessionKeys };
constructor(sessionKeys: SessionKeys) {
this._ = { sessionKeys };
}
}
/* eslint-enable */
export function sessionKeys( s : Partial<SessionArgs> ) {
return {
deviceId : s?.deviceId,
};
}
/**
* @returns a map of X-Causal headers, one for each session key
*/
function getCausalHeaders( s : Partial<SessionArgs>): Record<string, string> {
return {
"X-Causal-deviceId": s?.deviceId ?? "null",
};
}
function sseUrl( s : Partial<SessionArgs> ) {
let sseUrl = network.getBaseUrl().replace(
/\/?$/,
"/sse?id=");
sseUrl += s.deviceId;
return sseUrl;
}
/* eslint-disable */
/**
* Features to query, along with their arguments.
*
* A query is created by using either [[queryBuilder]] or [[createQuery]].
*
* A query is executed by calling either [[requestImpression]] or [[useImpression]].
*
*/
export class Query<T extends FeatureNames>{
/**
* Wraps a rating box that we can put on various product pages
* to collect ratings from our users
*/
getRatingBox( { product }
: { product : string } )
: Query<T | "RatingBox"> {
return this;
}
/**
* An empty feature to use only as a kill switch
*/
getProductInfo()
: Query<T | "ProductInfo"> {
return this;
}
/**
* Another feature just for demonstration purposes
*/
getFeature2( { exampleArg }
: { exampleArg : string } )
: Query<T | "Feature2"> {
return this;
}
/** @internal */
readonly _: {
_?: T; // T must be in the type for inference to work correctly
wireArgs: Record<string, unknown>;
} = {
wireArgs: {},
};
constructor() {
bindAllMethods(this);
}
}
/* eslint-enable */
/**
* The state of the feature flags when the FDL was compiled to this file.
*/
export const defaultFlags: Flags<FeatureNames> = {
RatingBox: true,
ProductInfo: true,
Feature2: true,
};
export class Session extends SessionEvents {
static fromDeviceId( deviceId: string, req?: IncomingMessage): Session {
const sessionArgs: Partial<SessionArgs> = { deviceId:deviceId };
return new Session(sessionArgs as SessionArgs, req);
}
//#endregion
// TSBase nogen
// TSBase nogen
/** @internal */
_: {
args: Partial<SessionArgs>;
sessionKeys: SessionKeys;
implicitArgs: ImplicitArgs;
cache: _Cache;
originator: "ssr" | "csr";
fromTransferredJson: boolean;
ssrTransfer: boolean;
ssrKeys: {
featureName: string;
strArgs: string;
}[];
// this tracks the number of times useImpression() returned with loading == true
// it's used a part of testing, to ensure we are not doing this incorrectly
loadingImpressionsCount: number;
// iserver communication information
commSnapshot: CommSnapshot;
};
constructor(args: SessionArgs, req?: IncomingMessage) {
super(sessionKeys(args));
const _backingStore = makeBackingStore(
_misc.ssr ? cacheOptions.ssrCacheType : cacheOptions.csrCacheType,
cacheOptions.makeCustomStore
);
const _cache = new _Cache(args, _backingStore, cacheOptions);
this._ = {
args,
cache: _cache,
implicitArgs: {},
originator: _misc.ssr ? "ssr" : "csr",
ssrTransfer: false,
ssrKeys: [],
loadingImpressionsCount: 0,
commSnapshot: {
fetches: 0,
featuresReceived: 0,
featuresRequested: 0,
errorsReceived: 0,
errorsAndWarnings: [],
},
sessionKeys: sessionKeys(args),
fromTransferredJson: false,
};
if (req) this.addIncomingMessageArgs(req);
bindAllMethods(this);
}
args(): SessionArgs {
return { ...this._.args } as SessionArgs;
}
/**
* Mark the session as still active
*/
keepAlive(): boolean {
// rate limit the keep alives to no more than 1 per second
if (Date.now() - Session.lastKeepAlive > 1000) {
Session.lastKeepAlive = Date.now();
network.sendBeacon(getCausalHeaders(sessionKeys(this._.args)), {
id: this._.args,
});
return true;
}
return false;
}
static lastKeepAlive = 0;
/**
* The currently active experiment variants. This is intended for reporting information to other
* systems. It should *not* be used as an input for any display or logic on your site.
*
* These are updated after a call to requestImpression, useImpression or useFeature
* The active variants will not be available until after the first call to one of these methods
*/
get activeVariants(): ActiveVariant[] {
if (
this._.commSnapshot.featuresRequested == 0 &&
!this._.fromTransferredJson
) {
_log.warn(
"session.activeVariants called before any features were requested"
);
}
return (this._.cache.get(activeVariantsKey) ?? []) as ActiveVariant[];
}
/**
* All the features that have been requested so far. This is intended for reporting information to other
* systems. It should *not* be used as an input for any display or logic on your site.
*/
get requestedFeatures(): RequestedFeature[] {
return (this._.cache.get(requestedFeaturesKey) ?? []) as RequestedFeature[];
}
/**
* Returns true if the call to session constructor [i.e. new Session()] created a new cache
* This is true iff
* - this is the first time creating a session
* - the previous session expired
* - the session was created with different session args then what was cached
* - you are using an ephemeral cache (e.g. in SSR)
*
* This call is useful in the browser to determine if you've created a new session
*/
get constructedNewCache(): boolean {
return this._.cache.isNew;
}
/** Returns information about this sessions communication with the impression server */
commSnapshot(): CommSnapshot {
return this._.commSnapshot;
}
/**
* Serializes a session to JSON. Used in conjunction with [[useSessionJSON]]. Useful to transfer a session for SSR.
*
* @returns the serialized JSON
*/
toJSON(): SessionJSON {
if (
this._.commSnapshot.fetches == 0 &&
this._.cache.cacheStats.hits.size == 0
) {
_log.warn(
"Session.toJSON() called before a call to requestImpression() or requestCacheFill()"
);
}
const cacheJson: Record<string, string> = {};
const featureJson: (_RequestStoreEntry & {
featureName: string;
strArgs: string;
})[] = [];
for (const key of this._.cache.backingStore.keys()) {
if (key.startsWith(nonFeaturePrefix)) {
const noPrefixKey = key.substring(nonFeaturePrefix.length);
if (noPrefixKey != cacheInfoKey) {
const value = this._.cache.backingStore.get(key) as string;
cacheJson[noPrefixKey] = value;
}
} else {
const featureName = key;
const featureEntry = this._.cache.backingStore.get(featureName) as
| FeatureEntry
| undefined;
if (featureEntry) {
for (const [strArgs, _entry] of Object.entries(featureEntry)) {
const entry = { ..._entry, featureName, strArgs };
featureJson.push(entry);
}
}
}
}
const sessionJson: SessionJSON = {
sessionArgs: this._.args,
cacheJson,
featureJson,
commSnapshotJson: this.commSnapshot(),
originator: this._.originator,
activeVariants: this.activeVariants,
};
// the line below removes all undefined attributes
// some frameworks do not like undefined across serialization boundaries
// most notably, next.js, see:
// https://github.com/vercel/next.js/discussions/11209
return JSON.parse(JSON.stringify(sessionJson));
}
/** @internal */
static fromJSON(
json: SessionJSON,
options?: {
/** If true, will delete any existing cache entries in a shared cache (like localStorage). Defaults to false. */
alwaysDelExistingCache?: boolean;
/**
* If true, will indicate to Causal that an SSR render occurred and only tranferred entries should render on the first tick
* Doing this prevents react hydration errors.
* After the first render, it is important to indicate that the SSR transfer is complete by calling [[Session.ssrTransferComplete]].
* The react hook [[useSessionJSON]] will handle this automatically
* Default to true if transfering from ssr to csr, otherwise false
*/
ssrTransfer?: boolean;
}
): Session {
const _options = {
...{
alwaysDelExistingCache: false,
ssrTransfer: json.originator == "ssr" && !_misc.ssr,
},
...options,
};
// if the session args are different,
// creating the session will (correctly) clear the cache
// it will also expire the cache if the cache is too old
const session = new Session(json.sessionArgs as SessionArgs);
session._.originator = json.originator;
session._.fromTransferredJson = true;
if (_options.alwaysDelExistingCache) session._.cache.backingStore.delAll();
const ssrTransfer = _options.ssrTransfer;
// transfer the cache entries
const cacheJson = json.cacheJson;
const featuresJson = json.featureJson;
if (cacheJson != undefined) {
for (const [k, v] of Object.entries(cacheJson)) {
if (v) {
try {
session._.cache.set(k, v);
} catch {
_log.warn("failed to restore non feature " + k);
}
}
}
}
// dump the transferred snapshot into the cache to make it easy to view in the browser
session._.cache.set("transferredCommSnapshot", json.commSnapshotJson);
if (featuresJson != undefined) {
for (const { featureName, strArgs, ...entry } of featuresJson) {
try {
const { created: _created, expires: _expires, ...rest } = entry;
const created = new Date(_created);
const expires = new Date(_expires);
session._.cache.setFeature(featureName, strArgs, {
...rest,
created,
expires,
});
} catch {
_log.warn(
`failed to restore feature entry ${featureName} ${strArgs}`
);
}
}
session._.ssrTransfer = ssrTransfer;
if (ssrTransfer) {
session._.ssrKeys = featuresJson
.filter(({ featureName }) => featureName != "session")
.map(({ featureName, strArgs }) => {
return { featureName, strArgs };
});
} else session._.ssrKeys = [];
}
return session;
}
/** @internal */
setSsrTransferComplete() {
if (this._.ssrTransfer) {
this._.ssrTransfer = false;
this._.ssrKeys = [];
}
}
/**
* Add implicit session arguments (such as the ip address) from the incoming message
* @param incomingMessage an HTTP IncomingMessage
*/
addIncomingMessageArgs(incomingMessage: IncomingMessage) {
this._.implicitArgs = {
...this._.args,
userAgent: incomingMessage?.headers["user-agent"] as string,
clientType: "typescript",
entryUrl: incomingMessage?.url,
};
}
/**
* Async function to get the impression and on/off flags associated with a feature.
*
* @returns A promise that will resolve with the impression and the current set of feature flags.
* On an error, it will return the default values for the impression and flags, as well as an additional informational error value.
*
* @typeparam Type information for the request and returned impression. Typically inferred from the query.
* @param query Features to request and their arguments.
* @param sessionArgs The session args as defined in the FDL
* @param impressionId The impression id.
*
*/
async requestImpression<Q extends Query<FeatureNames>>(
query: Q,
impressionId?: string
): Promise<{
impression: ImpressionType<Q>;
flags: FlagsType<Q>;
error?: ErrorTypes;
}> {
if (impressionId == undefined) impressionId = uuidv4();
return await requestImpression(this, query, impressionId);
}
/**
* Async function to fill the cache with impressions. This is typically used for SSR.
* This function will first test the cache to see if the requested impressions are already cached.
* If not it will fetch the impression and populate the cache.
* The cached impressions will not be logged and will not count towards any metrics until they are fetched from the cache
* by [[Session.requestImpression]] or [[useImpression]]
*
* @returns A promise that will resolve with the impression and the current set of feature flags.
* On an error, it will return the default values for the impression and flags, as well as an additional informational error value.
*
* @typeparam Type information for the request and returned impression. Typically inferred from the query.
* @param query Features to request and their arguments.
*
*/
async requestCacheFill<Q extends Query<FeatureNames>>(
query: Q
): Promise<void> {
await requestImpression(this, query, undefined);
}
/**
* Clear all impression stats. Resets cache hits, misses, and noops
*/
clearImpressionStats() {
this._.loadingImpressionsCount = 0;
this._.cache.clearCacheStats();
}
/**
* Get impression stats
* @returns returns features that have were served from cache (hits), not served from cache (misses), or not requested (noOps)
*/
getImpressionStats(): {
cacheMisses: string[];
cacheHits: string[];
cacheNoOps: string[];
loadingImpressions: number;
} {
const cacheStats = this._.cache.cacheStats;
const cacheHits = [...cacheStats.hits.keys()];
const cacheMisses = [...cacheStats.misses.keys()];
const loadingImpressions = this._.loadingImpressionsCount;
// perhaps this logic should live in the Cache class
const keys = this._.cache.backingStore.keys();
const cacheNoOps = keys.filter(
(k) =>
!k.startsWith(nonFeaturePrefix) &&
k != "session" &&
cacheStats.hits.get(k) == undefined &&
cacheStats.misses.get(k) == undefined
);
return {
cacheHits,
cacheMisses,
cacheNoOps,
loadingImpressions,
};
}
}
type OmitNever<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] };
type Writeable<T> = { -readonly [P in keyof T]: T[P] };
type UndefinedToNull<T> = {
[P in keyof T]-?: undefined extends T[P] ? T[P] | null : T[P];
};
export type FeatureNames = keyof typeof allFeatureTypes;
type SessionKeys = Partial<ReturnType<typeof sessionKeys>>;
export type Flags<T extends FeatureNames> = { [P in T]: boolean };
type _WireFlags = typeof defaultFlags;
export type Impression<T extends FeatureNames> = {
[P in keyof Pick<
_ImpressionImpl,
T | "toJSON" | "sessionKeys"
>]: _ImpressionImpl[P];
} & SessionEvents;
/**
* Represents the type of a query, both its features and arguments.
*
* This type generally will not be constructed manually, but instead be inferred from the return value of [[queryBuilder]] or [[createQuery]].
*
* @paramtype The feature to query for
*/
export type QueryArgs<T extends FeatureNames> = {
[F in T]: Parameters<Query<T>[`get${F}`]>[number] | Record<string, never>;
};
export function signalInstance(
feature: FeatureBase,
event: string,
args: unknown
) {
// this is default feature, can't really signal
if (feature._.impression == undefined) return;
if (feature._.impressionId == undefined) return;
signal(
feature.featureName,
event,
feature._.impression.sessionKeys,
feature._.impressionId,
args
);
}
function signalStatic(feature: string, event: string, argsArr: unknown[]) {
const arg0 = argsArr[0];
const sk =
arg0 instanceof Session
? sessionKeys(arg0.args())
: sessionKeys(arg0 as SessionArgs);
const impressionId = argsArr[1] as string;
const args = argsArr[2];
signal(feature, event, sk, impressionId, args);
}
function signalSession(
event: string,
session: Session | SessionKeys | SessionEvents,
args: unknown
): void {
const sk =
session instanceof Session
? sessionKeys(session.args())
: session instanceof SessionEvents
? sessionKeys(session._.sessionKeys)
: sessionKeys(session);
if (session instanceof Session) {
if (session._.commSnapshot.fetches == 0) {
_log.info(
"Possibly signaling a session event without requesting an impression. " +
"If the impression was requested with another Session with the same args, you can ignore this message."
);
}
}
signal(undefined, event, sk, undefined, args);
}
/**
* Create a query to use with [[requestImpression]] or [[useImpression]].
*
* @typeparam The names of the features to query for.
* @param args The arguments for each feature in T.
* @return Query to use with [[requestImpression]] or [[useImpression]].
*/
export function createQuery<T extends FeatureNames>(
args: QueryArgs<T>
): Query<T> {
const query = new Query();
query._.wireArgs = args;
return query as Query<T>;
}
export type FeatureNamesNoArgs = keyof OmitNever<{
[F in FeatureNames]: Parameters<Query<F>[`get${F}`]>[0] extends undefined
? F
: never;
}>;
/** This type represents the common portion of all features outputs */
type WireFeatureCommon = {
/** The imperssion id for this feature impression */
_impressionId: string;
/** Any variants that should be turned on if this feature goes from cacheOnly to a real impression */
_variants?: WireVariant[];
};
type AllFeatureClasses = {
[F in keyof typeof allFeatureTypes]: InstanceType<typeof allFeatureTypes[F]>;
};
type AFeatureOutput<F extends FeatureNames> = {
// eslint-disable-next-line
[P in keyof AllFeatureClasses[F]]: AllFeatureClasses[F][P] extends Function
? never
: AllFeatureClasses[F][P];
};
type FeatureOutputs = {
[F in FeatureNames]?: Omit<
OmitNever<Writeable<UndefinedToNull<AFeatureOutput<F>>>>,
"_" | "featureName"
>;
};
/** @internal */
export type _WireArgs = Partial<QueryArgs<FeatureNames>>;
/** @internal */
export type _WireOutputs = { session?: SessionResponse } & Partial<{
[P in FeatureNames]:
| (FeatureOutputs[P] & WireFeatureCommon)
| "OFF"
| "UNKNOWN";
}>;
function signal(
feature: string | undefined,
event: string,
sessionKeys: SessionKeys,
impressionId: string | undefined,
args: unknown
): void {
const _data = {
id: sessionKeys,
feature,
event,
impressionId,
args,
};
network.sendBeacon(getCausalHeaders(sessionKeys), _data);
}
// ImpressionBaseType and ImpressionBase are a bit of trickery
// to tell the TS compiler that ImpressionImp really does
// potentially have each of the feature classes as a member
type ImpressionBaseType = Partial<{
[F in keyof typeof allFeatureTypes]: InstanceType<typeof allFeatureTypes[F]>;
}> &
SessionEvents;
interface ImpressionBase {
new (sessionKeys: SessionKeys): ImpressionBaseType;
}
/** @internal */
export class _ImpressionImpl extends (SessionEvents as ImpressionBase) {
/** internal */
readonly _: { sessionKeys: SessionKeys; json: ImpressionJSON };
// Note: There is no impression id declared at this level
// The features have impression ids as part of their outputs
/**
* Serializes an impression to JSON. Used in conjunction with [[toImpression]]. Useful to transfer an impression for SSR.
*
* @returns the serialized JSON
*/
toJSON() {
return this._.json;
}
get sessionKeys() {
return this._.json.sessionKeys;
}
constructor(impressionJson: ImpressionJSON) {
super(impressionJson.sessionKeys);
this._ = { json: impressionJson, sessionKeys: impressionJson.sessionKeys };
const { wireOutputs, wireArgs } = impressionJson;
for (const featureName of Object.keys(wireArgs ?? {}) as (
| FeatureNames
| "session"
)[]) {
if (featureName == "session") continue;
const output = wireOutputs[featureName];
let shouldCreateFeature: boolean;
switch (impressionJson.impressionType) {
case "error":
shouldCreateFeature = defaultFlags[featureName];
break;
case "loading":
shouldCreateFeature = false;
break;
case "real":
if (output == "OFF") shouldCreateFeature = false;
else if (output == undefined || output == "UNKNOWN") {
_log.info(
"undefined, null or UNKNOWN output for " +
featureName +
". Using defaults."
);
shouldCreateFeature = defaultFlags[featureName];
} else shouldCreateFeature = true;
}
if (shouldCreateFeature) {
const constructor = allFeatureTypes[featureName as FeatureNames];
const feature = new constructor() as FeatureBase;
feature.featureName = featureName;
bindAllMethods(feature);
const featureOutputs = wireOutputs[featureName] as
| (WireFeatureCommon & Record<string, unknown>)
| undefined;
const featureArgs = wireArgs[featureName] as
| Record<string, unknown>
| undefined;
const impressionId = featureOutputs?._impressionId;
if (featureOutputs) {
feature._.impression = this;
feature._.impressionId = impressionId;
}
// if proxies are not supported (very old browswers), just return the defaults
if (typeof Proxy == "function") {
const handler = {
get(
target: typeof feature,
prop: string,
receiver: typeof feature
) {
// very hard to correctly proxy signal handler b/c of default parameters
if (prop.startsWith("signal")) {
return Reflect.get(target, prop, receiver);
}
// return args value
if (featureArgs?.[prop] !== undefined) {
return featureArgs[prop];
}
// return impression value
// if not available the default was the value initialized in the class
if (featureOutputs?.[prop] !== undefined) {
return featureOutputs[prop] ?? undefined; // null -> undefined (set so do not get default value)
}
return Reflect.get(target, prop, receiver);
},
};
this[featureName] = new Proxy(feature, handler) as never;
}
}
}
bindAllMethods(this);
}
}
// eslint-disable-next-line
function bindAllMethods(obj: any) {
// this is used in exported class constructors
// so that those classes can be destructured
// w/o worrying about "this" semantics
const props = Object.getOwnPropertyNames(Object.getPrototypeOf(obj));
props.forEach((prop) => {
const descriptor = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(obj),
prop
);
if (
descriptor &&
typeof descriptor.value === "function" &&
prop !== "constructor"
) {
obj[prop] = obj[prop].bind(obj);
}
});
}
type ImplicitArgs = {
userAgent?: string;
entryUrl?: string;
clientType?: string;
};
export type ImpressionType<Q> = Q extends Query<infer T>
? Impression<T>
: never;
export type FlagsType<Q> = Q extends Query<infer T> ? Flags<T> : never;
async function requestImpression<Q extends Query<FeatureNames>>(
session: Session,
query: Q,
/** if impressionId is undefined it is a cache fill */
impressionId: string | undefined
): Promise<{
impression: ImpressionType<Q>;
flags: FlagsType<Q>;
error?: ErrorTypes;
}> {
const cache = session._.cache;
const wireArgs = query._.wireArgs;
const { cachedImpression, cachedFlags } = _getCachedImpression(
session,
wireArgs
);
if (cachedImpression != undefined && cachedFlags != undefined) {
// signal and return the cached impression
let impression = cachedImpression;
if (impressionId != undefined) {
// impressionId != undefined means this is not a cache fill request
_updateSessionVariants(
session,
undefined,
impressionId,
cachedImpression
);
_sendImpressionBeacon(session, cachedImpression, impressionId);
impression = _updateImpressionIds(
cachedImpression,
impressionId,
wireArgs
);
}
return {
impression: impression as unknown as ImpressionType<Q>,
flags: cachedFlags as FlagsType<Q>, // cast needed for older version of TS
};
}
const fetchOptions: FetchOptions[] = [];
const {
flags,
impression,
error,
warning,
activeVariants,
featuresRequested,
featuresReceived,
registered,
} = await iserverFetch({
options: fetchOptions,
impressionId,
sessionArgs: session._.args,
implicitArgs: session._.implicitArgs,
wireArgs: wireArgs,
});
if (registered) {
session._.cache.set(causalRegisteredKey, "true");
} else {
session._.cache.del(causalRegisteredKey);
}
session._.commSnapshot.fetches += 1;
session._.commSnapshot.featuresRequested += featuresRequested;
session._.commSnapshot.featuresReceived += featuresReceived;
if (error) {
session._.commSnapshot.errorsReceived += 1;
session._.commSnapshot.errorsAndWarnings.unshift(error);
}
if (warning) {
session._.commSnapshot.errorsReceived += 1;
session._.commSnapshot.errorsAndWarnings.unshift(warning);
}