@conduit-client/service-cache 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,27 @@
1
+ *Attorney/Client Privileged + Confidential*
2
+
3
+ Terms of Use for Public Code (Non-OSS)
4
+
5
+ *NOTE:* Before publishing code under this license/these Terms of Use, please review https://salesforce.quip.com/WFfvAMKB18AL and confirm that you’ve completed all prerequisites described therein. *These Terms of Use may not be used or modified without input from IP and Product Legal.*
6
+
7
+ *Terms of Use*
8
+
9
+ Copyright 2022 Salesforce, Inc. All rights reserved.
10
+
11
+ These Terms of Use govern the download, installation, and/or use of this software provided by Salesforce, Inc. (“Salesforce”) (the “Software”), were last updated on April 15, 2022, ** and constitute a legally binding agreement between you and Salesforce. If you do not agree to these Terms of Use, do not install or use the Software.
12
+
13
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the Software and derivative works subject to these Terms. These Terms shall be included in all copies or substantial portions of the Software.
14
+
15
+ Subject to the limited rights expressly granted hereunder, Salesforce reserves all rights, title, and interest in and to all intellectual property subsisting in the Software. No rights are granted to you hereunder other than as expressly set forth herein. Users residing in countries on the United States Office of Foreign Assets Control sanction list, or which are otherwise subject to a US export embargo, may not use the Software.
16
+
17
+ Implementation of the Software may require development work, for which you are responsible. The Software may contain bugs, errors and incompatibilities and is made available on an AS IS basis without support, updates, or service level commitments.
18
+
19
+ Salesforce reserves the right at any time to modify, suspend, or discontinue, the Software (or any part thereof) with or without notice. You agree that Salesforce shall not be liable to you or to any third party for any modification, suspension, or discontinuance.
20
+
21
+ You agree to defend Salesforce against any claim, demand, suit or proceeding made or brought against Salesforce by a third party arising out of or accruing from (a) your use of the Software, and (b) any application you develop with the Software that infringes any copyright, trademark, trade secret, trade dress, patent, or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy (each a “Claim Against Salesforce”), and will indemnify Salesforce from any damages, attorney fees, and costs finally awarded against Salesforce as a result of, or for any amounts paid by Salesforce under a settlement approved by you in writing of, a Claim Against Salesforce, provided Salesforce (x) promptly gives you written notice of the Claim Against Salesforce, (y) gives you sole control of the defense and settlement of the Claim Against Salesforce (except that you may not settle any Claim Against Salesforce unless it unconditionally releases Salesforce of all liability), and (z) gives you all reasonable assistance, at your expense.
22
+
23
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA, OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
24
+
25
+ These Terms of Use shall be governed exclusively by the internal laws of the State of California, without regard to its conflicts of laws rules. Each party hereby consents to the exclusive jurisdiction of the state and federal courts located in San Francisco County, California to adjudicate any dispute arising out of or relating to these Terms of Use and the download, installation, and/or use of the Software. Except as expressly stated herein, these Terms of Use constitute the entire agreement between the parties, and supersede all prior and contemporaneous agreements, proposals, or representations, written or oral, concerning their subject matter. No modification, amendment, or waiver of any provision of these Terms of Use shall be effective unless it is by an update to these Terms of Use that Salesforce makes available, or is in writing and signed by the party against whom the modification, amendment, or waiver is to be asserted.
26
+
27
+ _*Data Privacy*_: Salesforce may collect, process, and store device, system, and other information related to your use of the Software. This information includes, but is not limited to, IP address, user metrics, and other data (“Usage Data”). Salesforce may use Usage Data for analytics, product development, and marketing purposes. You acknowledge that files generated in conjunction with the Software may contain sensitive or confidential data, and you are solely responsible for anonymizing and protecting such data.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ This software is provided as-is with no support provided.
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
File without changes
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ import { type DeepReadonly } from '@conduit-client/utils';
2
+ import { type Key } from './keys';
3
+ /**
4
+ * The "canonical" cache control metadata. Typically set by
5
+ * the server or the framework based on data annotations.
6
+ * Should be static.
7
+ */
8
+ export type CanonicalCacheControlMetadata = {
9
+ type: 'max-age';
10
+ maxAge: number;
11
+ } | {
12
+ type: 'stale-while-revalidate';
13
+ maxAge: number;
14
+ staleTime: number;
15
+ } | {
16
+ type: 'no-cache';
17
+ } | {
18
+ type: 'no-store';
19
+ };
20
+ /**
21
+ * The complete cache control metadata. This complete metadata
22
+ * is used for CacheEntries and includes runtime-generated information.
23
+ */
24
+ export type CacheControlMetadata = CanonicalCacheControlMetadata & {
25
+ generatedTime: number;
26
+ };
27
+ /**
28
+ * The namespace and type metadata for a given entry
29
+ */
30
+ export type CacheTypeMetadata = {
31
+ namespace: string;
32
+ name: string;
33
+ };
34
+ /**
35
+ * The type of store data required for a cache.
36
+ *
37
+ * Includes the description on the type of data, the cache control metadata, and the value
38
+ */
39
+ export type CacheEntry<T> = {
40
+ value: T;
41
+ metadata: {
42
+ cacheControl: CacheControlMetadata;
43
+ type: CacheTypeMetadata;
44
+ };
45
+ };
46
+ export type CacheEntrySet<T> = Omit<CacheEntry<T>, 'metadata'> & {
47
+ metadata: {
48
+ cacheControl: CacheControlMetadata | CanonicalCacheControlMetadata;
49
+ type?: CacheTypeMetadata;
50
+ };
51
+ };
52
+ /**
53
+ * The interface for a Cache store
54
+ */
55
+ export type Cache = {
56
+ get<T>(key: Key, options?: {
57
+ copy: boolean;
58
+ }): DeepReadonly<CacheEntry<T>> | CacheEntry<T> | undefined;
59
+ set<T>(key: Key, value: CacheEntrySet<T>): void;
60
+ delete(key: Key): void;
61
+ setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata): void;
62
+ length(): number;
63
+ keys(): Set<Key>;
64
+ entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]>;
65
+ record(): RecordableCache;
66
+ filter(predicate: FilterPredicate): Cache;
67
+ buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache;
68
+ };
69
+ export type ReadonlyCache = Pick<Cache, 'get' | 'length' | 'keys'> & {
70
+ filter(predicate: FilterPredicate): ReadonlyCache;
71
+ record(): RecordableReadonlyCache;
72
+ };
73
+ type RecordableProperties = {
74
+ keysRead: Set<Key>;
75
+ missingKeysRead: Set<Key>;
76
+ keysUpdated: Set<Key>;
77
+ };
78
+ export type RecordableReadonlyCache = ReadonlyCache & RecordableProperties;
79
+ export type RecordableCache = Cache & RecordableProperties;
80
+ export type FilterPredicate = (key: Key, value: CacheEntry<unknown>) => boolean;
81
+ export type IFixedTimeWritableCache = Cache;
82
+ export {};
@@ -0,0 +1,54 @@
1
+ import { type DeepReadonly } from '@conduit-client/utils';
2
+ import { type Key } from './keys';
3
+ import type { Cache, CacheControlMetadata, CacheEntry, CacheEntrySet, CanonicalCacheControlMetadata, FilterPredicate, IFixedTimeWritableCache, RecordableCache } from './cache';
4
+ export declare class DefaultCache implements Cache {
5
+ constructor();
6
+ protected data: Record<Key, CacheEntry<unknown>>;
7
+ /**
8
+ * Returns a cache entry at the specified key; undefined if no
9
+ * such entry exists.
10
+ *
11
+ * @param key store key
12
+ * @param [options] options for get (e.g. copy for deep copy)
13
+ */
14
+ get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;
15
+ get<T>(key: Key, options: {
16
+ copy: true;
17
+ }): CacheEntry<T> | undefined;
18
+ get<T>(key: Key, options: {
19
+ copy: false;
20
+ }): DeepReadonly<CacheEntry<T>> | undefined;
21
+ /**
22
+ * Adds the specified key/value to the cache.
23
+ *
24
+ * @param key key at which to store value
25
+ * @param entry value to be stored
26
+ */
27
+ set(key: Key, entry: CacheEntrySet<unknown>): void;
28
+ /**
29
+ * Removes the cache entry associated with the specified key.
30
+ *
31
+ * @param key key to be removed from the store
32
+ */
33
+ delete(key: Key): void;
34
+ /**
35
+ * Sets the metadata for the specified key if the key is in cache.
36
+ * If the key doesn't exist, it does nothing.
37
+ *
38
+ * @param key key at which to store metadata
39
+ * @param cacheControlMetadata metadata to be stored
40
+ */
41
+ setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata): void;
42
+ length(): number;
43
+ keys(): Set<Key>;
44
+ entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]>;
45
+ record(): RecordableCache;
46
+ filter(predicate: FilterPredicate): Cache;
47
+ buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache;
48
+ }
49
+ /**
50
+ A utility class for use in tests only
51
+ */
52
+ export declare class ClearableCache extends DefaultCache {
53
+ clear(): void;
54
+ }
@@ -0,0 +1,80 @@
1
+ import { type DeepReadonly } from '@conduit-client/utils';
2
+ import { type Key } from './keys';
3
+ import type { CacheEntry, Cache, RecordableCache, FilterPredicate, CacheControlMetadata, CacheEntrySet, IFixedTimeWritableCache, CanonicalCacheControlMetadata } from './cache';
4
+ /**
5
+ A utility class for recording actions made on a cache.
6
+ */
7
+ export declare class DefaultRecordableCache implements Cache {
8
+ protected baseCache: Cache;
9
+ constructor(baseCache: Cache);
10
+ keysRead: Set<Key>;
11
+ missingKeysRead: Set<Key>;
12
+ keysUpdated: Set<Key>;
13
+ metadataKeysUpdated: Set<Key>;
14
+ delete(key: Key): void;
15
+ get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;
16
+ get<T>(key: Key, options: {
17
+ copy: true;
18
+ }): CacheEntry<T> | undefined;
19
+ get<T>(key: Key, options: {
20
+ copy: false;
21
+ }): DeepReadonly<CacheEntry<T>> | undefined;
22
+ set<T>(key: Key, value: CacheEntrySet<T>): void;
23
+ setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata): void;
24
+ length(): number;
25
+ keys(): Set<string>;
26
+ entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]>;
27
+ record(): RecordableCache;
28
+ filter(predicate: FilterPredicate): Cache;
29
+ buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache;
30
+ }
31
+ /**
32
+ A utility class for filtering cache entries based on a given predicate.
33
+ */
34
+ export declare class DefaultFilteredCache implements Cache {
35
+ protected baseCache: Cache;
36
+ protected predicate: FilterPredicate;
37
+ constructor(baseCache: Cache, predicate: FilterPredicate);
38
+ delete(key: Key): void;
39
+ get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;
40
+ get<T>(key: Key, options: {
41
+ copy: true;
42
+ }): CacheEntry<T> | undefined;
43
+ get<T>(key: Key, options: {
44
+ copy: false;
45
+ }): DeepReadonly<CacheEntry<T>> | undefined;
46
+ set<T>(key: Key, value: CacheEntrySet<T>): void;
47
+ setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata): void;
48
+ length(): number;
49
+ keys(): Set<string>;
50
+ entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]>;
51
+ record(): RecordableCache;
52
+ filter(predicate: FilterPredicate): Cache;
53
+ private getFilteredEntries;
54
+ private getFilteredKeys;
55
+ buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache;
56
+ }
57
+ /**
58
+ A utility class for automatically setting the generated time on all write operations
59
+ */
60
+ export declare class FixedTimeWritableCache implements IFixedTimeWritableCache {
61
+ protected baseCache: Cache;
62
+ protected generatedTime: number;
63
+ constructor(baseCache: Cache, generatedTime: number);
64
+ delete(key: Key): void;
65
+ get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;
66
+ get<T>(key: Key, options: {
67
+ copy: true;
68
+ }): CacheEntry<T> | undefined;
69
+ get<T>(key: Key, options: {
70
+ copy: false;
71
+ }): DeepReadonly<CacheEntry<T>> | undefined;
72
+ set<T>(key: Key, value: CacheEntrySet<T>): void;
73
+ setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata): void;
74
+ length(): number;
75
+ keys(): Set<string>;
76
+ entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]>;
77
+ record(): RecordableCache;
78
+ filter(predicate: FilterPredicate): Cache;
79
+ buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache;
80
+ }
@@ -0,0 +1,9 @@
1
+ import { type Cache } from './cache';
2
+ import type { NamedService, ServiceDescriptor } from '@conduit-client/utils';
3
+ export { type Cache, type ReadonlyCache, type CacheControlMetadata, type CacheEntry, type CanonicalCacheControlMetadata, type FilterPredicate, type IFixedTimeWritableCache, } from './cache';
4
+ export type { Key } from './keys';
5
+ export type ICache = Cache;
6
+ export type NamedCacheService<Name extends string = 'cache'> = NamedService<Name, ICache>;
7
+ export type CacheServiceDescriptor = ServiceDescriptor<ICache, 'cache', '1.0'>;
8
+ export { ClearableCache } from './default';
9
+ export declare function buildServiceDescriptor(): CacheServiceDescriptor;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Code outside the cache implementation should treat keys as opaque
3
+ * values of this type.
4
+ */
5
+ export type Key = string;
@@ -0,0 +1,262 @@
1
+ /*!
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ /*!
7
+ * Copyright (c) 2022, Salesforce, Inc.,
8
+ * All rights reserved.
9
+ * For full license text, see the LICENSE.txt file
10
+ */
11
+ const { stringify, parse } = JSON;
12
+ function deepCopy(x) {
13
+ const stringified = stringify(x);
14
+ return stringified ? parse(stringified) : void 0;
15
+ }
16
+ class DefaultRecordableCache {
17
+ constructor(baseCache) {
18
+ this.baseCache = baseCache;
19
+ this.keysRead = /* @__PURE__ */ new Set();
20
+ this.missingKeysRead = /* @__PURE__ */ new Set();
21
+ this.keysUpdated = /* @__PURE__ */ new Set();
22
+ this.metadataKeysUpdated = /* @__PURE__ */ new Set();
23
+ }
24
+ delete(key) {
25
+ this.keysUpdated.add(key);
26
+ this.baseCache.delete(key);
27
+ }
28
+ get(key, options) {
29
+ this.keysRead.add(key);
30
+ const value = this.baseCache.get(key);
31
+ if (value === void 0) {
32
+ this.missingKeysRead.add(key);
33
+ }
34
+ if (options == null ? void 0 : options.copy) {
35
+ return deepCopy(value);
36
+ }
37
+ return value;
38
+ }
39
+ set(key, value) {
40
+ this.keysUpdated.add(key);
41
+ this.metadataKeysUpdated.add(key);
42
+ this.baseCache.set(key, value);
43
+ }
44
+ setMetadata(key, cacheControlMetadata) {
45
+ this.metadataKeysUpdated.add(key);
46
+ this.baseCache.setMetadata(key, cacheControlMetadata);
47
+ }
48
+ length() {
49
+ return this.baseCache.length();
50
+ }
51
+ keys() {
52
+ return this.baseCache.keys();
53
+ }
54
+ entries() {
55
+ return this.baseCache.entries();
56
+ }
57
+ record() {
58
+ return new DefaultRecordableCache(this);
59
+ }
60
+ filter(predicate) {
61
+ return new DefaultFilteredCache(this, predicate);
62
+ }
63
+ buildFixedTimeWritableCache(generatedTime) {
64
+ return new FixedTimeWritableCache(this, generatedTime);
65
+ }
66
+ }
67
+ class DefaultFilteredCache {
68
+ constructor(baseCache, predicate) {
69
+ this.baseCache = baseCache;
70
+ this.predicate = predicate;
71
+ }
72
+ delete(key) {
73
+ this.baseCache.delete(key);
74
+ }
75
+ get(key, options) {
76
+ const result = this.baseCache.get(key);
77
+ if (result && this.predicate(key, result)) {
78
+ if (options == null ? void 0 : options.copy) {
79
+ return deepCopy(result);
80
+ }
81
+ return result;
82
+ }
83
+ return void 0;
84
+ }
85
+ set(key, value) {
86
+ this.baseCache.set(key, value);
87
+ }
88
+ setMetadata(key, cacheControlMetadata) {
89
+ this.baseCache.setMetadata(key, cacheControlMetadata);
90
+ }
91
+ length() {
92
+ return this.getFilteredKeys().size;
93
+ }
94
+ keys() {
95
+ return this.getFilteredKeys();
96
+ }
97
+ entries() {
98
+ return this.getFilteredEntries();
99
+ }
100
+ record() {
101
+ return new DefaultRecordableCache(this);
102
+ }
103
+ filter(predicate) {
104
+ return new DefaultFilteredCache(this, predicate);
105
+ }
106
+ getFilteredEntries() {
107
+ return this.baseCache.entries().filter(([key, _value]) => {
108
+ return this.get(key);
109
+ });
110
+ }
111
+ getFilteredKeys() {
112
+ const filteredKeySet = /* @__PURE__ */ new Set();
113
+ this.baseCache.keys().forEach((key) => {
114
+ if (this.get(key)) {
115
+ filteredKeySet.add(key);
116
+ }
117
+ });
118
+ return filteredKeySet;
119
+ }
120
+ buildFixedTimeWritableCache(generatedTime) {
121
+ return new FixedTimeWritableCache(this, generatedTime);
122
+ }
123
+ }
124
+ class FixedTimeWritableCache {
125
+ constructor(baseCache, generatedTime) {
126
+ this.baseCache = baseCache;
127
+ this.generatedTime = generatedTime;
128
+ }
129
+ delete(key) {
130
+ this.baseCache.delete(key);
131
+ }
132
+ get(key, options) {
133
+ return this.baseCache.get(key, options);
134
+ }
135
+ set(key, value) {
136
+ this.baseCache.set(key, {
137
+ ...value,
138
+ metadata: {
139
+ ...value.metadata,
140
+ cacheControl: { ...value.metadata.cacheControl, generatedTime: this.generatedTime }
141
+ }
142
+ });
143
+ }
144
+ setMetadata(key, cacheControlMetadata) {
145
+ this.baseCache.setMetadata(key, {
146
+ ...cacheControlMetadata,
147
+ generatedTime: this.generatedTime
148
+ });
149
+ }
150
+ length() {
151
+ return this.baseCache.length();
152
+ }
153
+ keys() {
154
+ return this.baseCache.keys();
155
+ }
156
+ entries() {
157
+ return this.baseCache.entries();
158
+ }
159
+ record() {
160
+ return new DefaultRecordableCache(this);
161
+ }
162
+ filter(predicate) {
163
+ return new DefaultFilteredCache(this, predicate);
164
+ }
165
+ buildFixedTimeWritableCache(generatedTime) {
166
+ return new FixedTimeWritableCache(this, generatedTime);
167
+ }
168
+ }
169
+ class DefaultCache {
170
+ constructor() {
171
+ this.data = {};
172
+ }
173
+ get(key, options) {
174
+ if (options == null ? void 0 : options.copy) {
175
+ return deepCopy(this.data[key]);
176
+ }
177
+ return this.data[key];
178
+ }
179
+ /**
180
+ * Adds the specified key/value to the cache.
181
+ *
182
+ * @param key key at which to store value
183
+ * @param entry value to be stored
184
+ */
185
+ set(key, entry) {
186
+ if (entry.metadata.cacheControl.type === "no-store") {
187
+ return;
188
+ }
189
+ this.data[key] = {
190
+ ...entry,
191
+ metadata: {
192
+ ...entry.metadata,
193
+ type: entry.metadata.type || {
194
+ namespace: "OneStore:Internal",
195
+ name: "UnknownType"
196
+ },
197
+ cacheControl: {
198
+ generatedTime: Date.now() / 1e3,
199
+ ...entry.metadata.cacheControl
200
+ }
201
+ }
202
+ };
203
+ }
204
+ /**
205
+ * Removes the cache entry associated with the specified key.
206
+ *
207
+ * @param key key to be removed from the store
208
+ */
209
+ delete(key) {
210
+ delete this.data[key];
211
+ }
212
+ /**
213
+ * Sets the metadata for the specified key if the key is in cache.
214
+ * If the key doesn't exist, it does nothing.
215
+ *
216
+ * @param key key at which to store metadata
217
+ * @param cacheControlMetadata metadata to be stored
218
+ */
219
+ setMetadata(key, cacheControlMetadata) {
220
+ if (key in this.data) {
221
+ this.data[key].metadata.cacheControl = {
222
+ generatedTime: Date.now() / 1e3,
223
+ ...cacheControlMetadata
224
+ };
225
+ }
226
+ }
227
+ length() {
228
+ return this.keys().size;
229
+ }
230
+ keys() {
231
+ return new Set(Object.keys(this.data));
232
+ }
233
+ entries() {
234
+ return Object.entries(this.data);
235
+ }
236
+ record() {
237
+ return new DefaultRecordableCache(this);
238
+ }
239
+ filter(predicate) {
240
+ return new DefaultFilteredCache(this, predicate);
241
+ }
242
+ buildFixedTimeWritableCache(generatedTime) {
243
+ return new FixedTimeWritableCache(this, generatedTime);
244
+ }
245
+ }
246
+ class ClearableCache extends DefaultCache {
247
+ clear() {
248
+ this.data = {};
249
+ }
250
+ }
251
+ function buildServiceDescriptor() {
252
+ return {
253
+ type: "cache",
254
+ version: "1.0",
255
+ service: new DefaultCache()
256
+ };
257
+ }
258
+ export {
259
+ ClearableCache,
260
+ buildServiceDescriptor
261
+ };
262
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../utils/dist/index.js","../../src/v1/derived-caches.ts","../../src/v1/default.ts","../../src/v1/index.ts"],"sourcesContent":["/*!\n * Copyright (c) 2022, Salesforce, Inc.,\n * All rights reserved.\n * For full license text, see the LICENSE.txt file\n */\nfunction bfs(start, predicate, getChildren) {\n const queue = [...start];\n const visited = /* @__PURE__ */ new Set([...start]);\n const matches2 = /* @__PURE__ */ new Set();\n while (queue.length) {\n const curr = queue.shift();\n if (predicate(curr)) {\n matches2.add(curr);\n }\n const children = getChildren(curr);\n for (const child of children) {\n if (!visited.has(child)) {\n visited.add(child);\n queue.push(child);\n }\n }\n }\n return matches2;\n}\nfunction lineFormatter(position, message, filePath) {\n return `${message} (${filePath}:${position.line}:${position.column})`;\n}\nclass DefaultFileParserLogger {\n constructor(services, filePath) {\n this.services = services;\n this.filePath = filePath;\n }\n trace(position, message) {\n this.services.logger.trace(this.format(position, message));\n }\n debug(position, message) {\n this.services.logger.debug(this.format(position, message));\n }\n info(position, message) {\n this.services.logger.info(this.format(position, message));\n }\n warn(position, message) {\n this.services.logger.warn(this.format(position, message));\n }\n error(position, message) {\n this.services.logger.error(this.format(position, message));\n }\n format(position, message) {\n return lineFormatter(position, message, this.filePath);\n }\n}\nfunction matches(test, s) {\n if (test === void 0) {\n return false;\n } else if (typeof test === \"string\") {\n return s === test;\n } else if (test instanceof RegExp) {\n return test.test(s);\n } else if (typeof test === \"function\") {\n return test(s);\n }\n return test.some((m) => matches(m, s));\n}\nfunction includes(incexc, s) {\n if (matches(incexc.exclude, s)) {\n return false;\n }\n if (matches(incexc.include, s)) {\n return true;\n }\n if (incexc.include) {\n return false;\n }\n return true;\n}\nconst { create, freeze, keys, entries } = Object;\nconst { hasOwnProperty } = Object.prototype;\nconst { isArray } = Array;\nconst { push, indexOf, slice } = Array.prototype;\nconst { stringify, parse } = JSON;\nconst WeakSetConstructor = WeakSet;\nconst LogLevelMap = {\n TRACE: 4,\n DEBUG: 3,\n INFO: 2,\n WARN: 1,\n ERROR: 0\n};\nclass ConsoleLogger {\n constructor(level = \"WARN\", printer = console.log, formatter = (level2, message) => `${level2}: ${message}`) {\n this.level = level;\n this.printer = printer;\n this.formatter = formatter;\n this.messages = [];\n }\n trace(message) {\n this.log(\"TRACE\", message);\n }\n debug(message) {\n this.log(\"DEBUG\", message);\n }\n info(message) {\n this.log(\"INFO\", message);\n }\n warn(message) {\n this.log(\"WARN\", message);\n }\n error(message) {\n this.log(\"ERROR\", message);\n }\n log(level, message) {\n if (LogLevelMap[level] > LogLevelMap[this.level]) {\n return;\n }\n this.printer(this.formatter(level, message));\n }\n}\nfunction loggerService(level, printer, formatter) {\n return new ConsoleLogger(level, printer, formatter);\n}\nclass Ok {\n constructor(value) {\n this.value = value;\n }\n isOk() {\n return true;\n }\n isErr() {\n return !this.isOk();\n }\n}\nclass Err {\n constructor(error) {\n this.error = error;\n }\n isOk() {\n return false;\n }\n isErr() {\n return !this.isOk();\n }\n}\nconst ok = (value) => new Ok(value);\nconst err = (err2) => new Err(err2);\nclass DataNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"DataNotFoundError\";\n }\n}\nclass DataIncompleteError extends Error {\n constructor(message, partialData) {\n super(message);\n this.partialData = partialData;\n this.name = \"DataIncompleteError\";\n }\n}\nfunction isDataNotFoundError(error) {\n return error instanceof DataNotFoundError || error.name === \"DataNotFoundError\";\n}\nfunction isDataIncompleteError(error) {\n return error instanceof DataIncompleteError || error.name === \"DataIncompleteError\";\n}\nfunction isCacheHitOrError(value) {\n if (value.isErr() && (isDataIncompleteError(value.error) || isDataNotFoundError(value.error))) {\n return false;\n }\n return true;\n}\nfunction isCacheMiss(value) {\n return !isCacheHitOrError(value);\n}\nfunction isResult(value) {\n return value != null && typeof value === \"object\" && \"isOk\" in value && \"isErr\" in value && typeof value.isOk === \"function\" && typeof value.isErr === \"function\" && (value.isOk() === true && value.isErr() === false && \"value\" in value || value.isOk() === false && value.isErr() === true && \"error\" in value);\n}\nfunction setOverlaps(setA, setB) {\n for (const element of setA) {\n if (setB.has(element)) {\n return true;\n }\n }\n return false;\n}\nfunction setDifference(setA, setB) {\n const differenceSet = /* @__PURE__ */ new Set();\n for (const element of setA) {\n if (!setB.has(element)) {\n differenceSet.add(element);\n }\n }\n return differenceSet;\n}\nfunction addAllToSet(targetSet, sourceSet) {\n for (const element of sourceSet) {\n targetSet.add(element);\n }\n}\nconst toTypeScriptSafeIdentifier = (s) => s.length >= 1 ? s[0].replace(/[^$_\\p{ID_Start}]/u, \"_\") + s.slice(1).replace(/[^$\\u200c\\u200d\\p{ID_Continue}]/gu, \"_\") : \"\";\nfunction isSubscribable(obj) {\n return typeof obj === \"object\" && obj !== null && \"subscribe\" in obj && typeof obj.subscribe === \"function\" && \"refresh\" in obj && typeof obj.refresh === \"function\";\n}\nfunction isSubscribableResult(x) {\n if (!isResult(x)) {\n return false;\n }\n return isSubscribable(x.isOk() ? x.value : x.error);\n}\nfunction buildSubscribableResult(result, subscribe, refresh) {\n if (result.isOk()) {\n return ok({ data: result.value, subscribe, refresh });\n } else {\n return err({ failure: result.error, subscribe, refresh });\n }\n}\nfunction resolvedPromiseLike(result) {\n if (isPromiseLike(result)) {\n return result.then((nextResult) => nextResult);\n }\n return {\n then: (onFulfilled, _onRejected) => {\n try {\n return resolvedPromiseLike(onFulfilled(result));\n } catch (e) {\n if (onFulfilled === void 0) {\n return resolvedPromiseLike(result);\n }\n return rejectedPromiseLike(e);\n }\n }\n };\n}\nfunction rejectedPromiseLike(reason) {\n if (isPromiseLike(reason)) {\n return reason.then((nextResult) => nextResult);\n }\n return {\n then: (_onFulfilled, onRejected) => {\n if (typeof onRejected === \"function\") {\n try {\n return resolvedPromiseLike(onRejected(reason));\n } catch (e) {\n return rejectedPromiseLike(e);\n }\n }\n return rejectedPromiseLike(reason);\n }\n };\n}\nfunction isPromiseLike(x) {\n return typeof (x == null ? void 0 : x.then) === \"function\";\n}\nfunction racesync(values) {\n for (const value of values) {\n let settled = void 0;\n if (isPromiseLike(value)) {\n value.then(\n (_) => {\n settled = value;\n },\n (_) => {\n settled = value;\n }\n );\n } else {\n settled = resolvedPromiseLike(value);\n }\n if (settled !== void 0) {\n return settled;\n }\n }\n return Promise.race(values);\n}\nfunction withResolvers() {\n let resolve, reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\nfunction deepEquals(x, y) {\n if (x === void 0) {\n return y === void 0;\n } else if (x === null) {\n return y === null;\n } else if (y === null) {\n return x === null;\n } else if (isArray(x)) {\n if (!isArray(y) || x.length !== y.length) {\n return false;\n }\n for (let i = 0; i < x.length; ++i) {\n if (!deepEquals(x[i], y[i])) {\n return false;\n }\n }\n return true;\n } else if (typeof x === \"object\") {\n if (typeof y !== \"object\") {\n return false;\n }\n const xkeys = Object.keys(x);\n const ykeys = Object.keys(y);\n if (xkeys.length !== ykeys.length) {\n return false;\n }\n for (let i = 0; i < xkeys.length; ++i) {\n const key = xkeys[i];\n if (!deepEquals(x[key], y[key])) {\n return false;\n }\n }\n return true;\n }\n return x === y;\n}\nfunction stableJSONStringify(node) {\n if (node && node.toJSON && typeof node.toJSON === \"function\") {\n node = node.toJSON();\n }\n if (node === void 0) {\n return;\n }\n if (typeof node === \"number\") {\n return isFinite(node) ? \"\" + node : \"null\";\n }\n if (typeof node !== \"object\") {\n return stringify(node);\n }\n let i;\n let out;\n if (isArray(node)) {\n out = \"[\";\n for (i = 0; i < node.length; i++) {\n if (i) {\n out += \",\";\n }\n out += stableJSONStringify(node[i]) || \"null\";\n }\n return out + \"]\";\n }\n if (node === null) {\n return \"null\";\n }\n const objKeys = keys(node).sort();\n out = \"\";\n for (i = 0; i < objKeys.length; i++) {\n const key = objKeys[i];\n const value = stableJSONStringify(node[key]);\n if (!value) {\n continue;\n }\n if (out) {\n out += \",\";\n }\n out += stringify(key) + \":\" + value;\n }\n return \"{\" + out + \"}\";\n}\nfunction toError(x) {\n if (x instanceof Error) {\n return x;\n }\n return new Error(typeof x === \"string\" ? x : JSON.stringify(x));\n}\nfunction deepCopy(x) {\n const stringified = stringify(x);\n return stringified ? parse(stringified) : void 0;\n}\nfunction readableStreamToAsyncIterable(stream) {\n if (stream.locked) {\n return err(new Error(\"ReadableStream is already locked\"));\n }\n if (Symbol.asyncIterator in stream) {\n return ok(stream);\n }\n const reader = stream.getReader();\n return ok({\n [Symbol.asyncIterator]: () => ({\n next: async () => {\n try {\n const result = await reader.read();\n if (result.done) {\n try {\n reader.releaseLock();\n } catch {\n }\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: result.value\n };\n } catch (e) {\n try {\n reader.releaseLock();\n } catch {\n }\n throw e;\n }\n },\n return: async (value) => {\n try {\n await reader.cancel();\n } catch {\n }\n try {\n reader.releaseLock();\n } catch {\n }\n return { done: true, value };\n },\n throw: async (exception) => {\n try {\n await reader.cancel();\n } catch {\n }\n try {\n reader.releaseLock();\n } catch {\n }\n throw exception;\n }\n })\n });\n}\nfunction satisfies(provided, requested) {\n const providedN = provided.split(\".\").map((s) => parseInt(s));\n const requestedN = requested.split(\".\").map((s) => parseInt(s));\n return providedN[0] === requestedN[0] && providedN[1] >= requestedN[1];\n}\nfunction stringIsVersion(s) {\n const versionParts = s.split(\".\");\n return (versionParts.length === 2 || versionParts.length === 3) && versionParts.every((part) => part.match(/^\\d+$/));\n}\nvar HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {\n HttpStatusCode2[HttpStatusCode2[\"Ok\"] = 200] = \"Ok\";\n HttpStatusCode2[HttpStatusCode2[\"Created\"] = 201] = \"Created\";\n HttpStatusCode2[HttpStatusCode2[\"NoContent\"] = 204] = \"NoContent\";\n HttpStatusCode2[HttpStatusCode2[\"NotModified\"] = 304] = \"NotModified\";\n HttpStatusCode2[HttpStatusCode2[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpStatusCode2[HttpStatusCode2[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpStatusCode2[HttpStatusCode2[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpStatusCode2[HttpStatusCode2[\"NotFound\"] = 404] = \"NotFound\";\n HttpStatusCode2[HttpStatusCode2[\"ServerError\"] = 500] = \"ServerError\";\n HttpStatusCode2[HttpStatusCode2[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n return HttpStatusCode2;\n})(HttpStatusCode || {});\nfunction getFetchResponseFromAuraError(err2) {\n if (err2.data !== void 0 && err2.data.statusCode !== void 0) {\n let data = {};\n data = err2.data;\n if (err2.id !== void 0) {\n data.id = err2.id;\n }\n return new FetchResponse(data.statusCode, data);\n }\n return new FetchResponse(500, {\n error: err2.message\n });\n}\nasync function coerceResponseToFetchResponse(response) {\n const { status } = response;\n const responseHeaders = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n let responseBody = null;\n if (status !== 204) {\n const contentType = responseHeaders[\"content-type\"];\n responseBody = contentType && contentType.startsWith(\"application/json\") ? await response.json() : await response.text();\n }\n return new FetchResponse(status, responseBody, responseHeaders);\n}\nfunction getStatusText(status) {\n switch (status) {\n case 200:\n return \"OK\";\n case 201:\n return \"Created\";\n case 304:\n return \"Not Modified\";\n case 400:\n return \"Bad Request\";\n case 404:\n return \"Not Found\";\n case 500:\n return \"Server Error\";\n default:\n return `Unexpected HTTP Status Code: ${status}`;\n }\n}\nclass FetchResponse extends Error {\n constructor(status, body, headers) {\n super();\n this.status = status;\n this.body = body;\n this.headers = headers || {};\n this.ok = status >= 200 && this.status <= 299;\n this.statusText = getStatusText(status);\n }\n}\nconst deeplyFrozen = new WeakSetConstructor();\nfunction deepFreeze(value) {\n if (typeof value !== \"object\" || value === null || deeplyFrozen.has(value)) {\n return;\n }\n deeplyFrozen.add(value);\n if (isArray(value)) {\n for (let i = 0, len = value.length; i < len; i += 1) {\n deepFreeze(value[i]);\n }\n } else {\n const keys$1 = keys(value);\n for (let i = 0, len = keys$1.length; i < len; i += 1) {\n deepFreeze(value[keys$1[i]]);\n }\n }\n freeze(value);\n}\nfunction isScalar(value) {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || value === null || value === void 0;\n}\nfunction isScalarObject(value) {\n return Object.values(value).every((value2) => isScalar(value2));\n}\nfunction isScalarArray(value) {\n return value.every((item) => isScalar(item));\n}\nfunction encodeQueryParam(paramName, value, explode) {\n switch (typeof value) {\n case \"string\":\n return [`${paramName}=${encodeURIComponent(value)}`];\n case \"number\":\n case \"boolean\":\n return [`${paramName}=${value}`];\n case \"object\":\n if (value === null) {\n return [];\n }\n if (isArray(value)) {\n if (!isScalarArray(value)) {\n throw new Error(`Unsupported non-scalar array type for ${paramName}`);\n }\n if (explode) {\n return value.map(\n (item) => `${paramName}=${item ? encodeURIComponent(item) : item}`\n );\n }\n return [\n `${paramName}=${value.map((item) => item ? encodeURIComponent(item) : item).join(\",\")}`\n ];\n }\n if (!isScalarObject(value)) {\n throw new Error(`Unsupported non-scalar object type for ${paramName}`);\n }\n if (explode) {\n return entries(value).map(\n ([key, value2]) => `${key}=${value2 ? encodeURIComponent(value2) : value2}`\n );\n }\n return [\n `${paramName}=${entries(value).flat().map((item) => item ? encodeURIComponent(item) : item).join(\",\")}`\n ];\n default:\n return [];\n }\n}\nclass InternalError extends Error {\n constructor(data) {\n super();\n this.data = data;\n this.type = \"internal\";\n }\n}\nclass UserVisibleError extends Error {\n constructor(data) {\n super();\n this.data = data;\n this.type = \"user-visible\";\n }\n}\nfunction applyDecorators(baseCommand, decorators, options) {\n if (!decorators || decorators.length === 0) {\n return baseCommand;\n }\n return decorators.reduce((command, decorator) => decorator(command, options), baseCommand);\n}\nexport {\n isArray as ArrayIsArray,\n indexOf as ArrayPrototypeIndexOf,\n push as ArrayPrototypePush,\n slice as ArrayPrototypeSlice,\n ConsoleLogger,\n DataIncompleteError,\n DataNotFoundError,\n DefaultFileParserLogger,\n Err,\n FetchResponse,\n HttpStatusCode,\n InternalError,\n parse as JSONParse,\n stringify as JSONStringify,\n LogLevelMap,\n create as ObjectCreate,\n entries as ObjectEntries,\n freeze as ObjectFreeze,\n keys as ObjectKeys,\n hasOwnProperty as ObjectPrototypeHasOwnProperty,\n Ok,\n UserVisibleError,\n WeakSetConstructor,\n addAllToSet,\n applyDecorators,\n bfs,\n buildSubscribableResult,\n coerceResponseToFetchResponse,\n deepCopy,\n deepEquals,\n deepFreeze,\n encodeQueryParam,\n err,\n getFetchResponseFromAuraError,\n includes,\n isCacheHitOrError,\n isCacheMiss,\n isDataIncompleteError,\n isDataNotFoundError,\n isPromiseLike,\n isResult,\n isSubscribable,\n isSubscribableResult,\n lineFormatter,\n loggerService,\n ok,\n racesync,\n readableStreamToAsyncIterable,\n rejectedPromiseLike,\n resolvedPromiseLike,\n satisfies,\n setDifference,\n setOverlaps,\n stableJSONStringify,\n stringIsVersion,\n toError,\n toTypeScriptSafeIdentifier,\n withResolvers\n};\n//# sourceMappingURL=index.js.map\n","/* eslint-disable no-dupe-class-members */\nimport { type DeepReadonly, deepCopy } from '@conduit-client/utils';\nimport { type Key } from './keys';\nimport type {\n CacheEntry,\n Cache,\n RecordableCache,\n FilterPredicate,\n CacheControlMetadata,\n CacheEntrySet,\n IFixedTimeWritableCache,\n CanonicalCacheControlMetadata,\n} from './cache';\n\n/**\n A utility class for recording actions made on a cache.\n */\nexport class DefaultRecordableCache implements Cache {\n constructor(protected baseCache: Cache) {}\n\n keysRead: Set<Key> = new Set();\n missingKeysRead: Set<Key> = new Set();\n keysUpdated: Set<Key> = new Set();\n metadataKeysUpdated: Set<Key> = new Set();\n\n delete(key: Key) {\n this.keysUpdated.add(key);\n this.baseCache.delete(key);\n }\n\n get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(key: Key, options: { copy: true }): CacheEntry<T> | undefined;\n get<T>(key: Key, options: { copy: false }): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(key: Key, options?: { copy: boolean }) {\n this.keysRead.add(key);\n const value = this.baseCache.get<T>(key);\n if (value === undefined) {\n this.missingKeysRead.add(key);\n }\n\n if (options?.copy) {\n return deepCopy(value);\n }\n return value;\n }\n\n set<T>(key: Key, value: CacheEntrySet<T>): void {\n this.keysUpdated.add(key);\n this.metadataKeysUpdated.add(key);\n this.baseCache.set(key, value);\n }\n\n setMetadata(\n key: Key,\n cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata\n ): void {\n this.metadataKeysUpdated.add(key);\n this.baseCache.setMetadata(key, cacheControlMetadata);\n }\n\n length() {\n return this.baseCache.length();\n }\n\n keys() {\n return this.baseCache.keys();\n }\n\n entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]> {\n return this.baseCache.entries();\n }\n\n record(): RecordableCache {\n return new DefaultRecordableCache(this);\n }\n\n filter(predicate: FilterPredicate): Cache {\n return new DefaultFilteredCache(this, predicate);\n }\n\n buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache {\n return new FixedTimeWritableCache(this, generatedTime);\n }\n}\n\n/**\n A utility class for filtering cache entries based on a given predicate.\n */\nexport class DefaultFilteredCache implements Cache {\n constructor(\n protected baseCache: Cache,\n protected predicate: FilterPredicate\n ) {}\n\n delete(key: Key) {\n this.baseCache.delete(key);\n }\n\n get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(key: Key, options: { copy: true }): CacheEntry<T> | undefined;\n get<T>(key: Key, options: { copy: false }): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(\n key: Key,\n options?: { copy: boolean }\n ): DeepReadonly<CacheEntry<T>> | CacheEntry<T> | undefined {\n const result = this.baseCache.get<T>(key) as CacheEntry<T>;\n\n // if we're chaining filtered caches together, then it's possible the result will be undefined here\n if (result && this.predicate(key, result)) {\n if (options?.copy) {\n return deepCopy(result) as CacheEntry<T>;\n }\n return result as DeepReadonly<CacheEntry<T>>;\n }\n\n return undefined;\n }\n\n set<T>(key: Key, value: CacheEntrySet<T>): void {\n this.baseCache.set(key, value);\n }\n\n setMetadata(key: Key, cacheControlMetadata: CacheControlMetadata): void {\n this.baseCache.setMetadata(key, cacheControlMetadata);\n }\n\n length() {\n return this.getFilteredKeys().size;\n }\n\n keys() {\n return this.getFilteredKeys();\n }\n\n entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]> {\n return this.getFilteredEntries();\n }\n\n record(): RecordableCache {\n return new DefaultRecordableCache(this);\n }\n\n filter(predicate: FilterPredicate): Cache {\n return new DefaultFilteredCache(this, predicate);\n }\n\n private getFilteredEntries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]> {\n return this.baseCache.entries().filter(([key, _value]) => {\n return this.get(key);\n });\n }\n\n private getFilteredKeys(): Set<Key> {\n const filteredKeySet: Set<Key> = new Set();\n this.baseCache.keys().forEach((key) => {\n if (this.get(key)) {\n filteredKeySet.add(key);\n }\n });\n return filteredKeySet;\n }\n\n buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache {\n return new FixedTimeWritableCache(this, generatedTime);\n }\n}\n\n/**\n A utility class for automatically setting the generated time on all write operations\n */\nexport class FixedTimeWritableCache implements IFixedTimeWritableCache {\n constructor(\n protected baseCache: Cache,\n protected generatedTime: number\n ) {}\n\n delete(key: Key) {\n this.baseCache.delete(key);\n }\n\n get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(key: Key, options: { copy: true }): CacheEntry<T> | undefined;\n get<T>(key: Key, options: { copy: false }): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(\n key: Key,\n options?: { copy: boolean }\n ): DeepReadonly<CacheEntry<T>> | CacheEntry<T> | undefined {\n return this.baseCache.get(key, options);\n }\n\n set<T>(key: Key, value: CacheEntrySet<T>): void {\n this.baseCache.set(key, {\n ...value,\n metadata: {\n ...value.metadata,\n cacheControl: { ...value.metadata.cacheControl, generatedTime: this.generatedTime },\n },\n });\n }\n\n setMetadata(\n key: Key,\n cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata\n ): void {\n this.baseCache.setMetadata(key, {\n ...cacheControlMetadata,\n generatedTime: this.generatedTime,\n });\n }\n\n length() {\n return this.baseCache.length();\n }\n\n keys() {\n return this.baseCache.keys();\n }\n\n entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]> {\n return this.baseCache.entries();\n }\n\n record(): RecordableCache {\n return new DefaultRecordableCache(this);\n }\n\n filter(predicate: FilterPredicate): Cache {\n return new DefaultFilteredCache(this, predicate);\n }\n\n buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache {\n return new FixedTimeWritableCache(this, generatedTime);\n }\n}\n","/* eslint-disable no-dupe-class-members */\nimport { deepCopy, type DeepReadonly } from '@conduit-client/utils';\nimport { type Key } from './keys';\nimport {\n DefaultFilteredCache,\n DefaultRecordableCache,\n FixedTimeWritableCache,\n} from './derived-caches';\nimport type {\n Cache,\n CacheControlMetadata,\n CacheEntry,\n CacheEntrySet,\n CanonicalCacheControlMetadata,\n FilterPredicate,\n IFixedTimeWritableCache,\n RecordableCache,\n} from './cache';\n\nexport class DefaultCache implements Cache {\n constructor() {}\n\n protected data: Record<Key, CacheEntry<unknown>> = {};\n\n /**\n * Returns a cache entry at the specified key; undefined if no\n * such entry exists.\n *\n * @param key store key\n * @param [options] options for get (e.g. copy for deep copy)\n */\n get<T>(key: Key): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(key: Key, options: { copy: true }): CacheEntry<T> | undefined;\n get<T>(key: Key, options: { copy: false }): DeepReadonly<CacheEntry<T>> | undefined;\n get<T>(\n key: Key,\n options?: { copy: boolean }\n ): DeepReadonly<CacheEntry<T>> | CacheEntry<T> | undefined {\n if (options?.copy) {\n return deepCopy(this.data[key]) as CacheEntry<T>;\n }\n return this.data[key] as DeepReadonly<CacheEntry<T>>;\n }\n\n /**\n * Adds the specified key/value to the cache.\n *\n * @param key key at which to store value\n * @param entry value to be stored\n */\n set(key: Key, entry: CacheEntrySet<unknown>): void {\n if (entry.metadata.cacheControl.type === 'no-store') {\n return;\n }\n this.data[key] = {\n ...entry,\n metadata: {\n ...entry.metadata,\n type: entry.metadata.type || {\n namespace: 'OneStore:Internal',\n name: 'UnknownType',\n },\n cacheControl: {\n generatedTime: Date.now() / 1000,\n ...entry.metadata.cacheControl,\n },\n },\n };\n }\n\n /**\n * Removes the cache entry associated with the specified key.\n *\n * @param key key to be removed from the store\n */\n delete(key: Key): void {\n delete this.data[key];\n }\n\n /**\n * Sets the metadata for the specified key if the key is in cache.\n * If the key doesn't exist, it does nothing.\n *\n * @param key key at which to store metadata\n * @param cacheControlMetadata metadata to be stored\n */\n setMetadata(\n key: Key,\n cacheControlMetadata: CacheControlMetadata | CanonicalCacheControlMetadata\n ): void {\n if (key in this.data) {\n this.data[key].metadata.cacheControl = {\n generatedTime: Date.now() / 1000,\n ...cacheControlMetadata,\n };\n }\n }\n\n length(): number {\n return this.keys().size;\n }\n\n keys(): Set<Key> {\n return new Set(Object.keys(this.data));\n }\n\n entries(): Array<[key: Key, value: DeepReadonly<CacheEntry<unknown>>]> {\n return Object.entries(this.data) as Array<\n [key: Key, value: DeepReadonly<CacheEntry<unknown>>]\n >;\n }\n\n record(): RecordableCache {\n return new DefaultRecordableCache(this);\n }\n\n filter(predicate: FilterPredicate): Cache {\n return new DefaultFilteredCache(this, predicate);\n }\n\n buildFixedTimeWritableCache(generatedTime: number): IFixedTimeWritableCache {\n return new FixedTimeWritableCache(this, generatedTime);\n }\n}\n\n/**\n A utility class for use in tests only\n */\nexport class ClearableCache extends DefaultCache {\n clear() {\n this.data = {};\n }\n}\n","import { type Cache } from './cache';\nimport { DefaultCache } from './default';\nimport type { NamedService, ServiceDescriptor } from '@conduit-client/utils';\n\nexport {\n type Cache,\n type ReadonlyCache,\n type CacheControlMetadata,\n type CacheEntry,\n type CanonicalCacheControlMetadata,\n type FilterPredicate,\n type IFixedTimeWritableCache,\n} from './cache';\nexport type { Key } from './keys';\nexport type ICache = Cache;\nexport type NamedCacheService<Name extends string = 'cache'> = NamedService<Name, ICache>;\nexport type CacheServiceDescriptor = ServiceDescriptor<ICache, 'cache', '1.0'>;\n\nexport { ClearableCache } from './default';\n\nexport function buildServiceDescriptor(): CacheServiceDescriptor {\n return {\n type: 'cache',\n version: '1.0',\n service: new DefaultCache(),\n };\n}\n"],"names":[],"mappings":";;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+EA,MAAM,EAAE,WAAW,MAAK,IAAK;AA8R7B,SAAS,SAAS,GAAG;AACnB,QAAM,cAAc,UAAU,CAAC;AAC/B,SAAO,cAAc,MAAM,WAAW,IAAI;AAC5C;AC/VO,MAAM,uBAAwC;AAAA,EACjD,YAAsB,WAAkB;AAAlB,SAAA,YAAA;AAEtB,SAAA,+BAAyB,IAAA;AACzB,SAAA,sCAAgC,IAAA;AAChC,SAAA,kCAA4B,IAAA;AAC5B,SAAA,0CAAoC,IAAA;AAAA,EALK;AAAA,EAOzC,OAAO,KAAU;AACb,SAAK,YAAY,IAAI,GAAG;AACxB,SAAK,UAAU,OAAO,GAAG;AAAA,EAC7B;AAAA,EAKA,IAAO,KAAU,SAA6B;AAC1C,SAAK,SAAS,IAAI,GAAG;AACrB,UAAM,QAAQ,KAAK,UAAU,IAAO,GAAG;AACvC,QAAI,UAAU,QAAW;AACrB,WAAK,gBAAgB,IAAI,GAAG;AAAA,IAChC;AAEA,QAAI,mCAAS,MAAM;AACf,aAAO,SAAS,KAAK;AAAA,IACzB;AACA,WAAO;AAAA,EACX;AAAA,EAEA,IAAO,KAAU,OAA+B;AAC5C,SAAK,YAAY,IAAI,GAAG;AACxB,SAAK,oBAAoB,IA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KACA,sBACI;AACJ,QAAI,OAAO,KAAK,MAAM;AAClB,WAAK,KAAK,GAAG,EAAE,SAAS,eAAe;AAAA,QACnC,eAAe,KAAK,IAAA,IAAQ;AAAA,QAC5B,GAAG;AAAA,MAAA;AAAA,IAEX;AAAA,EACJ;AAAA,EAEA,SAAiB;AACb,WAAO,KAAK,OAAO;AAAA,EACvB;AAAA,EAEA,OAAiB;AACb,WAAO,IAAI,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC;AAAA,EACzC;AAAA,EAEA,UAAuE;AACnE,WAAO,OAAO,QAAQ,KAAK,IAAI;AAAA,EAGnC;AAAA,EAEA,SAA0B;AACtB,WAAO,IAAI,uBAAuB,IAAI;AAAA,EAC1C;AAAA,EAEA,OAAO,WAAmC;AACtC,WAAO,IAAI,qBAAqB,MAAM,SAAS;AAAA,EACnD;AAAA,EAEA,4BAA4B,eAAgD;AACxE,WAAO,IAAI,uBAAuB,MAAM,aAAa;AAAA,EACzD;AACJ;AAKO,MAAM,uBAAuB,aAAa;AAAA,EAC7C,QAAQ;AACJ,SAAK,OAAO,CAAA;AAAA,EAChB;AACJ;AChHO,SAAS,yBAAiD;AAC7D,SAAO;AAAA,IACH,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS,IAAI,aAAA;AAAA,EAAa;AAElC;"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@conduit-client/service-cache",
3
+ "version": "2.0.0",
4
+ "private": false,
5
+ "description": "OneStore Cache Service definition",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/salesforce-experience-platform-emu/luvio-next.git",
10
+ "directory": "packages/@conduit-client/services/cache"
11
+ },
12
+ "license": "SEE LICENSE IN LICENSE.txt",
13
+ "exports": {
14
+ "./v1": {
15
+ "import": "./dist/v1/index.js",
16
+ "types": "./dist/types/v1/index.d.ts",
17
+ "require": "./dist/v1/index.js"
18
+ }
19
+ },
20
+ "main": "dist/index.js",
21
+ "module": "./dist/main/index.js",
22
+ "types": "dist/types/index.d.ts",
23
+ "files": [
24
+ "dist/"
25
+ ],
26
+ "scripts": {
27
+ "build": "vite build && tsc --build --emitDeclarationOnly",
28
+ "clean": "rm -rf dist",
29
+ "test": "vitest run",
30
+ "test:size": "size-limit",
31
+ "watch": "npm run build --watch"
32
+ },
33
+ "dependencies": {
34
+ "@conduit-client/service-instrumentation": "2.0.0",
35
+ "@conduit-client/utils": "2.0.0"
36
+ },
37
+ "volta": {
38
+ "extends": "../../../../package.json"
39
+ },
40
+ "size-limit": [
41
+ {
42
+ "path": "./dist/v1/index.js",
43
+ "limit": "1.5 kB"
44
+ }
45
+ ]
46
+ }