Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 | 143x 126x 126x 126x 126x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 2302x 2302x 2302x 2302x 2302x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 1272x 1272x 1272x 1272x 1272x 1272x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 8x 8x 8x 8x 8x 8x 8x 8x 13x 13x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 103x 103x 126x 837x 837x 837x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 143x 39x 38x 38x 39x 143x 2x 2x 2x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 143x 6x 3x 3x 3x 3x 3x 1x 1x 1x 3x 6x 143x 143x 11x 4x 4x 4x 11x 143x 190x 143x 143x 323x 143x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 296x 296x 296x 296x 296x 296x 323x 296x 296x 296x 296x 323x 323x 1x 1x 1x 1x 1x 1x 323x 323x 323x 295x 295x 295x 295x 323x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 295x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 143x 32x 323x 323x 323x 323x 323x 323x 143x 143x 143x 143x 143x 143x 143x 323x 323x 323x 323x 10x 10x 10x 10x 6x 10x 10x 7x 1x 1x 1x 1x 1x 1x 1x 7x 7x 143x 323x 323x 323x 321x 321x 321x 321x 321x 323x 323x 323x 323x 323x 323x 10x 143x 323x 323x 323x 323x 143x 1x 1x 1x 1x 1x 143x 1x 1x 1x 1x 143x 307x 307x 307x 307x 307x 307x 307x 2456x 2456x 2456x 2456x 2456x 2456x 616x 307x 309x 309x 309x 309x 307x 307x 307x 307x 307x 307x 307x 307x 307x 143x 9x 9x 9x 9x 4x 4x 4x 9x 143x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 5x 3x 2x 2x 1x 1x 1x 143x 242x 242x 242x 242x 242x 143x 183x 183x 183x 183x 183x 183x 183x 143x 3x 143x 944x 944x 944x 944x 944x 944x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 296x 296x 296x 296x 296x 296x 143x 7x 7x 7x 7x 7x 7x 143x 5x 40x 40x 40x 40x 40x 40x 143x 1340x 143x 143x 38x 38x 38x 38x 38x 38x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 143x 143x 143x 143x 143x 143x 143x 143x 89x 89x 89x 89x 185x 185x 185x 185x 185x 185x 185x 185x 89x 89x 89x 89x 89x 89x 89x 89x 185x 185x 185x 185x 181x 185x 89x 23x 23x 17x 17x 17x 17x 17x 17x 17x 169x 169x 169x 169x 169x 169x 17x 17x 17x 17x 17x 17x 169x 169x 169x 169x 169x 169x 169x 169x 17x 17x 23x 89x 89x 89x 89x 19x 185x 185x 185x 185x 185x 185x 185x 185x 31x 31x 185x 143x 143x 143x 143x 143x 143x 86x 86x 86x 86x 86x 86x 86x 86x 86x 20x 1x 86x 86x 19x 19x 19x 19x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 143x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 21x 21x 17x 17x 17x 17x 16x 16x 17x 17x 17x 1x 1x 1x 1x 1x 1x 1x 17x 15x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 16x 16x 16x 16x 16x 16x 16x 143x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 143x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 6x 6x 6x 3x 6x 6x 2x 2x 4x 4x 4x 4x 4x 4x 4x 3x 3x 4x 3x 3x 4x 143x 267x 267x 267x 267x 267x 267x 267x 126x 126x 143x 69x 69x 69x 69x 143x 183x 183x 183x 183x 183x 183x 183x 183x 183x 143x 6x 6x 6x 143x 143x 1x 143x 111x 111x 111x 111x 111x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 143x 143x 143x 143x 7x 7x 7x 7x 1x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 143x 18x 18x 18x 2x 2x 143x 12x 12x 12x 12x 12x 12x 12x 12x 12x 37x 37x 37x 37x 37x 37x 37x 37x 72x 37x 37x 12x 12x 7x 7x 7x 7x 7x 12x 12x 12x 7x 7x 7x 7x 7x 7x 7x 7x 32x 32x 32x 32x 32x 63x 25x 25x 25x 63x 32x 32x 32x 7x 7x 7x 32x 32x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 32x 12x 143x 103x 103x 103x 103x 103x 103x 103x 2x 2x 2x 2x 2x 103x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 143x 143x 143x 143x 143x 143x | import { property } from 'lit/decorators.js';
import {
fetchResults,
getUrl,
getAssets,
Asset,
WebResponse,
postUrl,
postJSON,
postForm,
getCookie
} from '../utils';
import {
ContactField,
ContactGroup,
CompletionOption,
CompletionSchema,
KeyedAssets,
CustomEventType,
Workspace,
Shortcut,
DirtyTrackable
} from '../interfaces';
import { RapidElement } from '../RapidElement';
import {
RealtimeSubscription,
setRealtimeContext,
subscribeToOrganization,
OrganizationEvent
} from '../live/Realtime';
import { Watchers } from '../live/Watchers';
import { lru } from 'tiny-lru';
import { DateTime } from 'luxon';
import { css, html } from 'lit';
import { configureLocalization } from '@lit/localize';
import { sourceLocale, targetLocales } from '../locales/locale-codes';
import { getFullName } from '../display/TembaUser';
import {
AppState,
DependencyResolver,
getDependencyResolver,
setDependencyResolver,
zustand
} from './AppState';
import { StoreApi } from 'zustand/vanilla';
import { normalizeUuid } from './identity';
const { setLocale } = configureLocalization({
sourceLocale,
targetLocales,
loadLocale: (locale) => import(`./locales/${locale}.js`)
});
export const getStore = () => {
return document.querySelector('temba-store') as Store;
};
export const STORE_ASSET_TYPES = [
'channel',
'contact',
'field',
'flow',
'global',
'group',
'label',
'llm',
'optin',
'template',
'topic',
'user'
] as const;
export type StoreAssetType = (typeof STORE_ASSET_TYPES)[number];
export interface StoreAssetReference {
type: StoreAssetType;
uuid?: string;
key?: string;
}
export interface StoreAsset extends StoreAssetReference {
name: string;
}
export interface StoreAssetChangedEvent {
type: 'asset_changed';
asset: StoreAsset;
}
export type StoreAssetHandler = (event: StoreAssetChangedEvent | null) => void;
interface AssetWatcher {
interests: StoreAssetReference[];
onEvent: StoreAssetHandler;
}
const STORE_ASSET_TYPE_SET = new Set<string>(STORE_ASSET_TYPES);
// the endpoint rejects a request carrying more than this many identifiers
const ASSET_BATCH_SIZE = 100;
// long-lived pages (a flow list paged through many times) would otherwise
// accumulate an entry for every asset ever seen. Once an entry is evicted the
// component falls back to the name its own response carried, and the identity
// is fetched again next time it is asked for.
export const ASSET_CACHE_SIZE = 500;
/**
* Versions are held well above the asset cache because losing one doesn't just
* forget a name, it drops the in-flight guard for that identity - and `assets`
* is bumped by reads that never touch `assetVersions`, so the two ages drift
* apart. Entries are a single number, so the extra headroom is cheap.
*/
export const ASSET_VERSION_CACHE_SIZE = ASSET_CACHE_SIZE * 8;
const isStoreAssetType = (type: string): type is StoreAssetType =>
STORE_ASSET_TYPE_SET.has(type);
const assetIdentity = (
asset: { type?: string; uuid?: string; key?: string } | null
): string | null => {
if (!asset || !isStoreAssetType(asset.type)) {
return null;
}
const identity = asset.uuid ? normalizeUuid(asset.uuid) : asset.key;
return identity ? `${asset.type}:${identity}` : null;
};
const watchesAsset = (watcher: AssetWatcher, asset: StoreAsset): boolean => {
const identity = assetIdentity(asset);
return (
!!identity &&
watcher.interests.some((interest) => assetIdentity(interest) === identity)
);
};
declare const __TEMBA_DEV_SERVER__: boolean;
/**
* True only when running against the temba-components dev server, which
* replaces `__TEMBA_DEV_SERVER__` with `true` at serve time. The production
* rollup build and the test runner replace it with `false`; for any other
* consumer the token is undefined and the try/catch falls back to `false`.
* We deliberately do not key off `process.env.NODE_ENV` — the published IIFE
* bundle (rollup.components.mjs) hardcodes that to 'development', so it can't
* distinguish the dev server from a production consumer.
*/
const isDevServer = (): boolean => {
try {
return __TEMBA_DEV_SERVER__ === true;
} catch {
return false;
}
};
export class Store extends RapidElement {
public static get styles() {
return css`
:host {
position: fixed;
z-index: 1000;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
top: 0.5em;
}
`;
}
settings = {};
@property({ type: Number })
ttl = 60000;
@property({ type: Number })
max = 20;
@property({ type: Boolean })
ready = false;
@property({ type: Boolean })
loader = false;
@property({ type: String, attribute: 'completion' })
completionEndpoint: string;
@property({ type: String, attribute: 'fields' })
fieldsEndpoint: string;
@property({ type: String, attribute: 'groups' })
groupsEndpoint: string;
@property({ type: String, attribute: 'assets' })
assetsEndpoint: string;
@property({ type: String, attribute: 'globals' })
globalsEndpoint: string;
@property({ type: String, attribute: 'workspace' })
workspaceEndpoint: string;
@property({ type: String, attribute: 'shortcuts' })
shortcutsEndpoint: string;
// current workspace and user uuids, used to address user-scoped realtime
// channels - hydrated by the page template
@property({ type: String })
org: string;
@property({ type: String })
user: string;
@property({ type: String })
brand = '';
@property({ type: Object, attribute: false })
private schema: CompletionSchema;
@property({ type: Object, attribute: false })
private fnOptions: CompletionOption[];
@property({ type: Object, attribute: false })
private keyedAssets: KeyedAssets = {};
private locale = [...navigator.languages];
private fields: { [key: string]: ContactField } = {};
private groups: { [uuid: string]: ContactGroup } = {};
private shortcuts: Shortcut[] = [];
private workspace: Workspace;
private featuredFields: ContactField[] = [];
private assetWatchers = new Watchers<AssetWatcher>('store asset watcher');
// canonical names, the identities we've already asked about (including ones
// the endpoint had no asset for) and their last-write versions, all bounded
// so a long-lived page doesn't keep every asset it has ever rendered
private assets = lru<StoreAsset>(ASSET_CACHE_SIZE);
private resolvedAssetIdentities = lru<boolean>(ASSET_CACHE_SIZE);
private assetVersions = lru<number>(ASSET_VERSION_CACHE_SIZE);
private pendingAssetRequests = new Map<string, Promise<void>>();
private assetVersion = 0;
// bumped by reset(), which only firstUpdated() calls today - the guard exists
// so a future caller that resets a live store can't have the cleared cache
// repopulated by a batch that was already in flight
private assetGeneration = 0;
private organizationWatch: RealtimeSubscription = null;
private organizationSubscribed = false;
private previousDependencyResolver: DependencyResolver = null;
private dependencyResolver: DependencyResolver = (dependencies) =>
this.resolveAssets(dependencies);
// http promise to monitor for completeness
public initialHttpComplete: Promise<void | WebResponse[]>;
private dirtyElements: DirtyTrackable[] = [];
public markDirty(ele: DirtyTrackable) {
if (!this.dirtyElements.includes(ele)) {
this.dirtyElements.push(ele);
}
}
public cleanAll() {
this.dirtyElements.forEach((ele) => ele.markClean());
this.dirtyElements = [];
}
public markClean(ele: DirtyTrackable) {
this.dirtyElements = this.dirtyElements.filter((el) => el !== ele);
}
public getDirtyMessage() {
if (this.dirtyElements.length > 0) {
return (
this.dirtyElements[0].dirtyMessage ||
'You have unsaved changes, are you sure you want to continue?'
);
}
}
private cache: any;
// user avatar urls by user uuid, seeded from server-hydrated user
// references so ones that arrive without an avatar (e.g. events published
// over sockets) can be filled in from users we've already seen. LRU-bounded
// so long-lived tabs don't accumulate every user ever seen.
private userAvatars = lru<string>(500);
public setUserAvatar(uuid: string, avatar: string) {
if (uuid && avatar) {
this.userAvatars.set(uuid, avatar);
}
}
public getUserAvatar(uuid: string): string {
return this.userAvatars.get(uuid);
}
public getLocale() {
return this.locale[0];
}
public clearCache() {
this.cache = lru(this.max, this.ttl);
}
public reset() {
const appState = this.getState();
this.ready = false;
this.clearCache();
this.settings = JSON.parse(getCookie('settings') || '{}');
zustand.setState({ brand: this.brand });
this.groups = {};
this.assets.clear();
this.resolvedAssetIdentities.clear();
this.pendingAssetRequests.clear();
this.assetVersions.clear();
this.assetVersion = 0;
this.assetGeneration++;
/*
// This will create a shorthand unit
this.humanizer.addLanguage("en", {
y: () => "y",
mo: () => "mo",
w: () => "w",
d: () => "d",
h: () => "h",
m: () => "m",
s: () => "s",
ms: () => "ms",
decimal: ".",
});
*/
const fetches = [];
if (this.completionEndpoint) {
fetches.push(
getUrl(this.getCompletionEndpoint()).then((response) => {
this.schema = response.json['context'] as CompletionSchema;
this.fnOptions = response.json['functions'] as CompletionOption[];
})
);
}
if (this.fieldsEndpoint) {
fetches.push(this.refreshFields());
}
if (this.globalsEndpoint) {
fetches.push(
getAssets(this.globalsEndpoint).then((assets: Asset[]) => {
this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);
})
);
}
if (this.groupsEndpoint) {
fetches.push(
getAssets<ContactGroup>(this.groupsEndpoint).then((groups) => {
for (const group of groups) {
this.groups[group.uuid] = group;
}
})
);
}
if (this.workspaceEndpoint) {
appState.fetchWorkspace(this.workspaceEndpoint);
fetches.push(
getUrl(this.workspaceEndpoint).then((response: WebResponse) => {
this.workspace = response.json;
const lang = response.headers.get('content-language');
if (lang) {
this.locale = [lang, ...this.locale];
}
})
);
}
if (this.shortcutsEndpoint) {
fetches.push(this.refreshShortcuts());
}
this.initialHttpComplete = Promise.all(fetches);
this.initialHttpComplete.then(() => {
this.ready = true;
});
}
public getShortcuts() {
return this.shortcuts || [];
}
public connectedCallback(): void {
super.connectedCallback();
// lit only runs firstUpdated once, so a store that is detached and
// re-attached has to reinstall its page hooks here
if (this.hasUpdated) {
this.installPageHooks();
}
}
public firstUpdated() {
this.installPageHooks();
this.reset();
}
/**
* Installs the hooks this store owns on behalf of the page: the canonical
* name resolver and the workspace realtime subscription. Idempotent so it
* can run again when a store is re-attached.
*/
private installPageHooks(): void {
if (getDependencyResolver() !== this.dependencyResolver) {
this.previousDependencyResolver = setDependencyResolver(
this.dependencyResolver
);
}
if (this.org && this.user) {
setRealtimeContext({ org: this.org, user: this.user });
if (!this.organizationWatch) {
this.organizationWatch = subscribeToOrganization(
(event) => this.handleOrganizationEvent(event),
() => {
if (this.organizationSubscribed) {
this.refreshAssetCache().catch((error) => {
console.error('failed to refresh store assets', error);
});
}
this.organizationSubscribed = true;
}
);
}
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
// only hand the resolver back if we're still the installed one, otherwise
// a store that never installed it would clear the live store's resolver
if (getDependencyResolver() === this.dependencyResolver) {
setDependencyResolver(this.previousDependencyResolver);
}
this.previousDependencyResolver = null;
if (this.organizationWatch) {
this.organizationWatch.unsubscribe();
this.organizationWatch = null;
}
}
public getLanguageCode() {
if (this.locale.length > 0) {
return this.locale[0].split('-')[0];
}
return 'en';
}
public async refreshGlobals() {
return getAssets(this.globalsEndpoint).then((assets: Asset[]) => {
this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);
});
}
public async refreshShortcuts() {
return getAssets(this.shortcutsEndpoint).then((shortcuts: Shortcut[]) => {
this.shortcuts = shortcuts;
});
}
public async refreshFields() {
return getAssets(this.fieldsEndpoint).then((assets: Asset[]) => {
this.keyedAssets['fields'] = [];
this.featuredFields = [];
assets.forEach((field: ContactField) => {
this.keyedAssets['fields'].push(field.key);
this.fields[field.key] = field;
if (field.featured) {
this.featuredFields.push(field);
}
});
this.featuredFields.sort((a, b) => {
return b.priority - a.priority;
});
this.keyedAssets['fields'].sort();
this.fireCustomEvent(CustomEventType.StoreUpdated, {
url: this.fieldsEndpoint,
data: this.keyedAssets['fields']
});
});
}
public shiftAndRound(duration, unit: string, singular: string) {
const value = Math.round(duration.shiftTo(unit).get(unit));
if (value == 1) {
return `1 ${singular}`;
} else {
return `${value} ${unit}`;
}
}
public getCountdown(futureDate: DateTime) {
const duration = futureDate.diff(DateTime.now());
const comps = duration.rescale();
if (comps.months > 0) {
return '> 1 month';
}
if (comps.days > 1) {
return `~ ${this.shiftAndRound(comps, 'days', 'day')}`;
}
if (comps.hours > 0) {
return `~ ${this.shiftAndRound(comps, 'hours', 'hour')}`;
}
return `~ ${this.shiftAndRound(comps, 'minutes', 'minute')}`;
}
public getShortDuration(scheduled: DateTime, compareDate: DateTime = null) {
const now = compareDate || DateTime.now();
return scheduled
.setLocale(this.locale[0])
.toRelative({ base: now, style: 'long' });
}
public getShortDurationFromIso(isoDateA: string, isoDateB: string = null) {
const scheduled = DateTime.fromISO(isoDateA);
const now = isoDateB ? DateTime.fromISO(isoDateB) : DateTime.now();
return this.getShortDuration(scheduled, now);
}
public setKeyedAssets(name: string, values: string[]): void {
this.keyedAssets[name] = values;
}
public updated(changedProperties: Map<string, any>) {
super.updated(changedProperties);
if (changedProperties.has('ready') && this.ready) {
const locale = this.getLanguageCode();
const target = targetLocales.find(
(targetLocale) => targetLocale === locale
);
if (target) {
setLocale(target);
}
}
}
/**
* Resolves the completion endpoint to fetch. When running against the
* temba-components dev server we override the configured endpoint so the
* editor serves our own editor.json (static/mr/docs/en-us/editor.json)
* rather than the host application's mailroom completions. The dev-server
* origin is derived from import.meta.url so this works even when the
* components are loaded cross-origin (e.g. rapidpro on :8001 with the
* components dev server on :3011).
*/
private getCompletionEndpoint(): string {
if (isDevServer()) {
try {
const origin = new URL(import.meta.url).origin;
return `${origin}/api/v2/completion.json`;
} catch {
// import.meta.url unavailable; fall back to the configured endpoint
}
}
return this.completionEndpoint;
}
public getCompletionSchema(): CompletionSchema {
return this.schema;
}
public getFunctions(): CompletionOption[] {
return this.fnOptions;
}
public getKeyedAssets(): KeyedAssets {
return this.keyedAssets;
}
public getFieldKeys(): string[] {
return this.keyedAssets['fields'] || [];
}
public getContactField(key: string): ContactField {
return this.fields[key];
}
public getFeaturedFields(): ContactField[] {
return this.featuredFields;
}
public getAsset(type: string, identity: string): StoreAsset | null {
if (!isStoreAssetType(type) || !identity) {
return null;
}
// the identity may be a key (cached verbatim, and case-sensitive) or a uuid
// (cached under its canonical form), so try verbatim first — a canonical
// uuid already hits on that pass, and keys never reach the normalizing one
return (
this.assets.get(`${type}:${identity}`) ||
this.assets.get(`${type}:${normalizeUuid(identity)}`) ||
null
);
}
/** Adds server-authoritative assets to the page cache. Components whose
* own response already contains canonical names can seed the same cache
* without making another request. */
public cacheAssets(assets: StoreAsset[]): void {
for (const asset of assets) {
this.cacheAsset(asset);
}
}
/** Resolves every requested reference from the cache, fetching only the
* identities this page hasn't resolved before. Concurrent callers share
* each in-flight batch and absent assets are negatively cached. */
public async resolveAssets(
requested: { type: string; uuid?: string; key?: string }[],
force = false
): Promise<StoreAsset[]> {
const references = new Map<string, StoreAssetReference>();
for (const candidate of requested || []) {
if (!isStoreAssetType(candidate.type)) {
continue;
}
const reference: StoreAssetReference = {
type: candidate.type,
...(candidate.uuid ? { uuid: candidate.uuid } : {}),
...(candidate.key ? { key: candidate.key } : {})
};
const identity = assetIdentity(reference);
if (identity) {
references.set(identity, reference);
}
}
const waits = new Set<Promise<void>>();
const missing: StoreAssetReference[] = [];
for (const [identity, reference] of references) {
const pending = this.pendingAssetRequests.get(identity);
if (pending) {
waits.add(pending);
} else if (force || !this.resolvedAssetIdentities.has(identity)) {
missing.push(reference);
}
}
if (this.assetsEndpoint) {
for (
let offset = 0;
offset < missing.length;
offset += ASSET_BATCH_SIZE
) {
const batch = missing.slice(offset, offset + ASSET_BATCH_SIZE);
const pending = this.fetchAssetBatch(batch);
waits.add(pending);
for (const reference of batch) {
const identity = assetIdentity(reference);
if (identity) {
this.pendingAssetRequests.set(identity, pending);
}
}
const cleanup = () => {
for (const reference of batch) {
const identity = assetIdentity(reference);
if (
identity &&
this.pendingAssetRequests.get(identity) === pending
) {
this.pendingAssetRequests.delete(identity);
}
}
};
void pending.then(cleanup, cleanup);
}
}
// one failed batch mustn't discard the names the others resolved
await Promise.all(
[...waits].map((wait) =>
wait.catch((error) => {
console.error('failed to resolve assets', error);
})
)
);
const resolved: StoreAsset[] = [];
for (const identity of references.keys()) {
const asset = this.assets.get(identity);
if (asset) {
resolved.push(asset);
}
}
return resolved;
}
/**
* Registers interest in workspace asset changes. An eventless delivery
* lets the watcher apply anything already cached and is repeated after a
* reconnect refresh; live changes carry the changed asset.
*/
public watchAssets(
requested: { type: string; uuid?: string; key?: string }[],
onEvent: StoreAssetHandler
): RealtimeSubscription {
const watcher: AssetWatcher = {
// an interest without an identifier is dropped rather than treated as a
// type wildcard, matching how resolveAssets ignores those references
interests: (requested || [])
.filter(
(interest) =>
isStoreAssetType(interest.type) && !!(interest.uuid || interest.key)
)
.map((interest) => ({
type: interest.type as StoreAssetType,
...(interest.uuid ? { uuid: interest.uuid } : {}),
...(interest.key ? { key: interest.key } : {})
})),
onEvent
};
this.assetWatchers.add(watcher);
this.assetWatchers.prime(watcher, () => watcher.onEvent(null));
return {
unsubscribe: () => {
this.assetWatchers.remove(watcher);
}
};
}
/**
* Refetches the assets the page is currently displaying after a reconnect,
* when we may have missed changes. Only live interests are refreshed - the
* identities we resolved for content that has since scrolled away would
* otherwise fan out into a request per hundred for no visible benefit.
*/
private async refreshAssetCache(): Promise<void> {
const interests = new Map<string, StoreAssetReference>();
for (const watcher of this.assetWatchers.all()) {
for (const interest of watcher.interests) {
const identity = assetIdentity(interest);
if (identity) {
interests.set(identity, interest);
}
}
}
if (interests.size > 0) {
await this.resolveAssets([...interests.values()], true);
}
this.assetWatchers.each((watcher) => watcher.onEvent(null));
}
private async fetchAssetBatch(
references: StoreAssetReference[]
): Promise<void> {
if (!this.assetsEndpoint || references.length === 0) {
return;
}
const generation = this.assetGeneration;
// undefined means "no write recorded", which is not the same as version 0:
// assetVersions is bounded, so an evicted entry must not be read as a
// newer write and throw away a perfectly fresh name
const startVersions = new Map<string, number | undefined>();
const requested = new Set<string>();
const payload: Partial<Record<StoreAssetType, string[]>> = {};
for (const reference of references) {
const identity = assetIdentity(reference);
const value = reference.uuid || reference.key;
if (!identity || !value) {
continue;
}
requested.add(identity);
startVersions.set(identity, this.assetVersions.get(identity));
(payload[reference.type] ||= []).push(value);
}
const response = await postJSON(this.assetsEndpoint, payload);
if (generation !== this.assetGeneration) {
return;
}
// postJSON only rejects on a server error, so a 4xx arrives here as an
// empty body - bail before the bookkeeping below negatively caches every
// requested identity for the life of the page
if (response.status < 200 || response.status >= 300) {
console.warn(
`asset request failed with status ${response.status}`,
payload
);
return;
}
for (const candidate of response.json?.results || []) {
// the endpoint echoes normalized uuids, which assetIdentity matches back
// to whatever form the reference was embedded in
const identity = assetIdentity(candidate);
if (
identity &&
requested.has(identity) &&
typeof candidate.name === 'string' &&
this.isCurrentAssetVersion(identity, startVersions.get(identity))
) {
this.cacheAsset(candidate as StoreAsset);
}
}
// Remember every requested identity, including assets the endpoint
// omitted, so deleted/missing references aren't repeatedly fetched.
for (const identity of requested) {
this.resolvedAssetIdentities.set(identity, true);
}
}
/**
* True when nothing has written this identity since the given version was
* read. A version we no longer have (evicted from the bounded map) can't
* prove a newer write, so the response is allowed through - keeping a name
* we know is stale forever is the worse failure.
*
* Note what that costs when it happens: the write it can't see may be a live
* socket rename that landed mid-batch, so this doesn't merely fail to protect
* a name we've forgotten, it can overwrite a fresher one we still hold. That
* needs an eviction inside a single batch's flight time, which is why
* ASSET_VERSION_CACHE_SIZE is kept well clear of the asset cache; the next
* socket event or reconnect refresh heals it either way.
*/
private isCurrentAssetVersion(
identity: string,
startVersion: number | undefined
): boolean {
const current = this.assetVersions.get(identity);
return current === undefined || current === startVersion;
}
private cacheAsset(asset: StoreAsset): void {
const identity = assetIdentity(asset);
if (!identity || typeof asset.name !== 'string') {
return;
}
this.assets.set(identity, { ...asset });
this.resolvedAssetIdentities.set(identity, true);
// every direct write is newer than any batch already in flight, so bump
// the version to discard a response that read an older name
this.assetVersions.set(identity, ++this.assetVersion);
}
private handleOrganizationEvent(event: OrganizationEvent): void {
const asset = event?.asset;
const identity = assetIdentity(asset);
if (
event?.type !== 'asset_changed' ||
!identity ||
typeof asset.name !== 'string'
) {
return;
}
const changed = { ...asset };
const interested = this.assetWatchers.some((watcher) =>
watchesAsset(watcher, changed)
);
const previouslyResolved = this.resolvedAssetIdentities.has(identity);
const pending = this.pendingAssetRequests.has(identity);
const legacyGroup =
changed.type === 'group' &&
changed.uuid &&
Object.prototype.hasOwnProperty.call(this.groups, changed.uuid);
if (legacyGroup) {
this.groups[changed.uuid] = {
...this.groups[changed.uuid],
uuid: changed.uuid,
name: changed.name
};
}
if (!previouslyResolved && !pending && !interested) {
return;
}
// cacheAsset records the write version, discarding any batch in flight
// for this identity that read the name before this change
this.cacheAsset(changed);
const publication: StoreAssetChangedEvent = {
type: 'asset_changed',
asset: changed
};
this.assetWatchers.each(
(watcher) => watcher.onEvent(publication),
(watcher) => watchesAsset(watcher, changed)
);
}
public isDynamicGroup(uuid: string): boolean {
const group = this.groups[uuid];
// we treat missing groups as dynamic since the
// api excludes initializing groups
if (!group) {
// console.warn('No group for ' + uuid);
}
if (!group || group.query) {
return true;
}
return false;
}
public getWorkspace(): Workspace {
return this.workspace;
}
public formatDate(dateString: string) {
return DateTime.fromISO(dateString)
.setLocale(this.getLocale())
.toLocaleString(DateTime.DATETIME_SHORT);
}
public postJSON(url: string, payload: any = '') {
return postJSON(url, payload);
}
public postForm(url: string, payload: any | FormData, headers: any = {}) {
return postForm(url, payload, headers);
}
public postUrl(
url: string,
payload: any = '',
headers: any = {},
contentType = null
) {
return postUrl(url, payload, headers, contentType);
}
public getUrl(
url: string,
options?: {
force?: boolean;
skipCache?: boolean;
controller?: AbortController;
headers?: { [key: string]: string };
}
): Promise<WebResponse> {
options = options || {};
if (!options.force && this.cache.has(url)) {
return new Promise<WebResponse>((resolve) => {
resolve(this.cache.get(url));
});
}
return getUrl(url, options.controller, options.headers || {}).then(
(response: WebResponse) => {
return new Promise<WebResponse>((resolve, reject) => {
if (response.status >= 200 && response.status <= 300) {
if (!options.skipCache) {
this.cache.set(url, response);
}
resolve(response);
} else {
reject('Status: ' + response.status);
}
});
}
);
}
private pendingResolves = {};
/**
* Fetches all of the results for a given API endpoint with caching
* @param url
*/
public getResults(
url: string,
options?: { force?: boolean }
): Promise<any[]> {
options = options || {};
const key = 'results_' + url;
const results = this.cache.get(key);
if (!options.force && results) {
return new Promise<any[]>((resolve) => {
resolve(results);
});
}
return new Promise<any[]>((resolve) => {
const pending = this.pendingResolves[url] || [];
pending.push(resolve);
this.pendingResolves[url] = pending;
if (pending.length <= 1) {
fetchResults(url).then((results: any[]) => {
this.cache.set(key, results);
const pending = this.pendingResolves[url] || [];
while (pending.length > 0) {
const resolve = pending.pop();
resolve(results);
}
});
}
});
}
public fetching: { [url: string]: number } = {};
public updateCache(url: string, data: any) {
this.cache.set(url, data);
this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });
}
public removeFromCache(url: string) {
this.cache.delete(url);
}
public resolveUsers(items: any, keys: string[]): Promise<void> {
return new Promise<void>((resolve) => {
const uuids = new Set<string>();
// keys are dot notation paths to user fields
items.forEach((item) => {
keys.forEach((key) => {
const parts = key.split('.');
let value = item;
for (let i = 0; i < parts.length; i++) {
value = value[parts[i]];
if (!value) {
break;
}
}
if (value && value.uuid) {
uuids.add(value.uuid);
}
});
});
const promises = [];
// we don't want to fetch all users at once so we can benefit from caching
uuids.forEach((uuid) => {
promises.push(
this.getUrl(`/api/v2/users.json?uuid=${encodeURIComponent(uuid)}`, {
force: true
})
);
});
// wait for all of our user fetches to complete
Promise.all(promises).then((promises) => {
promises.forEach((response: WebResponse) => {
if (response && response.json) {
const results = response.json.results;
if (results && results.length === 1) {
const user = results[0];
this.setUserAvatar(user.uuid, user.avatar);
items.forEach((item) => {
// replace each key with a matching user
keys.forEach((key) => {
const parts = key.split('.');
let value = item;
let last = value;
for (let i = 0; i < parts.length; i++) {
last = value;
value = value[parts[i]];
if (!value) {
break;
}
}
if (value && value.email === user.email) {
// only care about avatars for now
const orginalUser = last[parts[parts.length - 1]];
orginalUser.avatar = user.avatar;
orginalUser.name = getFullName(user);
orginalUser.uuid = user.uuid;
last[parts[parts.length - 1]].avatar = user.avatar;
}
});
});
}
}
});
resolve();
});
});
}
public makeRequest(
url: string,
options?: { force?: boolean; prepareData?: (data: any) => any }
) {
const previousRequest = this.fetching[url];
const now = new Date().getTime();
// if the request was recently made, don't do anything
if (previousRequest) {
setTimeout(() => {
this.makeRequest(url, options);
}, 500);
return;
}
let cached = this.cache.get(url);
if (cached && !options.force) {
cached = options.prepareData ? options.prepareData(cached) : cached;
this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data: cached });
} else {
options = options || {};
this.fetching[url] = now;
fetchResults(url).then((data) => {
if (!data) {
delete this.fetching[url];
return;
}
this.cache.set(url, data);
delete this.fetching[url];
data = options.prepareData ? options.prepareData(data) : data;
this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });
});
}
}
public get(key: string, defaultValue: any = null) {
return this.settings[key] || defaultValue;
}
public set(key: string, value: string) {
this.settings[key] = value;
// not sure yet if we really want to perist these
// setCookie(COOKIE_KEYS.SETTINGS, JSON.stringify(this.settings), '/');
}
public render() {
if (!this.ready && this.loader) {
return html`<temba-loading size="10" units="8"></temba-loading>`;
}
}
public getCompletions(type: string) {
const info = this.getState().flowInfo;
if (type === 'results') {
return info.results.map((result) => result.key);
} else if (type === 'locals') {
return info.locals;
}
return this.keyedAssets[type] || [];
}
public getApp(): StoreApi<AppState> {
return zustand;
}
public getState(): AppState {
return zustand.getState();
}
}
|