@tutao/tutanota-utils 3.89.24 → 3.91.2

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/lib/Encoding.js DELETED
@@ -1,329 +0,0 @@
1
- // @flow
2
-
3
- export type Base64 = string
4
- export type Base64Ext = string
5
- export type Base64Url = string
6
- export type Hex = string
7
-
8
- // TODO rename methods according to their JAVA counterparts (e.g. Uint8Array == bytes, Utf8Uint8Array == bytes...)
9
-
10
- export function uint8ArrayToArrayBuffer(uint8Array: Uint8Array): ArrayBuffer {
11
- if (uint8Array.byteLength === uint8Array.buffer.byteLength) {
12
- return uint8Array.buffer
13
- } else {
14
- return new Uint8Array(uint8Array).buffer // create a new instance with the correct length, if uint8Array is only a DataView on a longer Array.buffer
15
- }
16
- }
17
-
18
-
19
- /**
20
- * Converts a hex coded string into a base64 coded string.
21
- *
22
- * @param hex A hex encoded string.
23
- * @return A base64 encoded string.
24
- */
25
- export function hexToBase64(hex: Hex): Base64 {
26
- return uint8ArrayToBase64(hexToUint8Array(hex))
27
- }
28
-
29
- /**
30
- * Converts a base64 coded string into a hex coded string.
31
- *
32
- * @param base64 A base64 encoded string.
33
- * @return A hex encoded string.
34
- */
35
- export function base64ToHex(base64: Base64): Hex {
36
- return uint8ArrayToHex(base64ToUint8Array(base64))
37
- }
38
-
39
- /**
40
- * Converts a base64 string to a url-conform base64 string. This is used for
41
- * base64 coded url parameters.
42
- *
43
- * @param base64 The base64 string.
44
- * @return The base64url string.
45
- */
46
- export function base64ToBase64Url(base64: Base64): Base64Url {
47
- let base64url = base64.replace(/\+/g, "-")
48
- base64url = base64url.replace(/\//g, "_")
49
- base64url = base64url.replace(/=/g, "")
50
- return base64url
51
- }
52
-
53
- function makeLookup(str: string): {[string]: number} {
54
- const lookup = {}
55
- for (let i = 0; i < str.length; i++) {
56
- lookup[str.charAt(i)] = i;
57
- }
58
- return lookup
59
- }
60
-
61
- const base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
62
- const base64Lookup = makeLookup(base64Alphabet)
63
- const base64extAlphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
64
- const base64ExtLookup = makeLookup(base64extAlphabet)
65
-
66
- /**
67
- * Converts a base64 string to a base64ext string. Base64ext uses another character set than base64 in order to make it sortable.
68
- *
69
- *
70
- * @param base64 The base64 string.
71
- * @return The base64Ext string.
72
- */
73
- export function base64ToBase64Ext(base64: Base64): Base64Ext {
74
- base64 = base64.replace(/=/g, "")
75
- let base64ext = ""
76
- for (let i = 0; i < base64.length; i++) {
77
- let index = base64Lookup[base64.charAt(i)]
78
- base64ext += base64extAlphabet[index]
79
- }
80
- return base64ext
81
- }
82
-
83
- /**
84
- * Converts a Base64Ext string to a Base64 string and appends the padding if needed.
85
- * @param base64ext The base64Ext string
86
- * @returns The base64 string
87
- */
88
- export function base64ExtToBase64(base64ext: Base64Ext): Base64 {
89
- let base64 = ""
90
- for (let i = 0; i < base64ext.length; i++) {
91
- const index = base64ExtLookup[base64ext.charAt(i)]
92
- base64 += base64Alphabet[index]
93
- }
94
- let padding
95
- if (base64.length % 4 === 2) {
96
- padding = "=="
97
- } else if (base64.length % 4 === 3) {
98
- padding = "="
99
- } else {
100
- padding = ""
101
- }
102
- return base64 + padding
103
- }
104
-
105
- /**
106
- * Converts a base64 url string to a "normal" base64 string. This is used for
107
- * base64 coded url parameters.
108
- *
109
- * @param base64url The base64 url string.
110
- * @return The base64 string.
111
- */
112
- export function base64UrlToBase64(base64url: Base64Url): Base64 {
113
- let base64 = base64url.replace(/-/g, "+")
114
- base64 = base64.replace(/_/g, "/")
115
- let nbrOfRemainingChars = base64.length % 4
116
- if (nbrOfRemainingChars === 0) {
117
- return base64
118
- } else if (nbrOfRemainingChars === 2) {
119
- return base64 + "=="
120
- } else if (nbrOfRemainingChars === 3) {
121
- return base64 + "="
122
- }
123
- throw new Error("Illegal base64 string.")
124
- }
125
-
126
- // just for edge, as it does not support TextEncoder yet
127
- export function _stringToUtf8Uint8ArrayLegacy(string: string): Uint8Array {
128
- let fixedString
129
- try {
130
- fixedString = encodeURIComponent(string)
131
- } catch (e) {
132
- fixedString = encodeURIComponent(_replaceLoneSurrogates(string)) // we filter lone surrogates as trigger URIErrors, otherwise (see https://github.com/tutao/tutanota/issues/618)
133
- }
134
- let utf8 = unescape(fixedString)
135
- let uint8Array = new Uint8Array(utf8.length)
136
- for (let i = 0; i < utf8.length; i++) {
137
- uint8Array[i] = utf8.charCodeAt(i)
138
- }
139
- return uint8Array
140
- }
141
-
142
- const REPLACEMENT_CHAR = '\uFFFD'
143
-
144
- export function _replaceLoneSurrogates(s: ?string): string {
145
- if (s == null) {
146
- return ""
147
- }
148
- let result = []
149
- for (let i = 0; i < s.length; i++) {
150
- let code = s.charCodeAt(i)
151
- let char = s.charAt(i)
152
- if (0xD800 <= code && code <= 0xDBFF) {
153
- if (s.length === i) {
154
- // replace high surrogate without following low surrogate
155
- result.push(REPLACEMENT_CHAR)
156
- } else {
157
- let next = s.charCodeAt(i + 1)
158
- if (0xDC00 <= next && next <= 0xDFFF) {
159
- result.push(char)
160
- result.push(s.charAt(i + 1))
161
- i++ // valid high and low surrogate, skip next low surrogate check
162
- } else {
163
- result.push(REPLACEMENT_CHAR)
164
- }
165
- }
166
- } else if (0xDC00 <= code && code <= 0xDFFF) {
167
- // replace low surrogate without preceding high surrogate
168
- result.push(REPLACEMENT_CHAR)
169
- } else {
170
- result.push(char)
171
- }
172
- }
173
- return result.join("")
174
- }
175
-
176
- const encoder = (typeof TextEncoder == "function" ? new TextEncoder() : {encode: _stringToUtf8Uint8ArrayLegacy})
177
- const decoder = (typeof TextDecoder == "function" ? new TextDecoder() : {decode: _utf8Uint8ArrayToStringLegacy})
178
-
179
- /**
180
- * Converts a string to a Uint8Array containing a UTF-8 string data.
181
- *
182
- * @param string The string to convert.
183
- * @return The array.
184
- */
185
- export function stringToUtf8Uint8Array(string: string): Uint8Array {
186
- return encoder.encode(string)
187
- }
188
-
189
- // just for edge, as it does not support TextDecoder yet
190
- export function _utf8Uint8ArrayToStringLegacy(uint8Array: Uint8Array): string {
191
- let stringArray = []
192
- stringArray.length = uint8Array.length
193
- for (let i = 0; i < uint8Array.length; i++) {
194
- stringArray[i] = String.fromCharCode(uint8Array[i])
195
- }
196
- return decodeURIComponent(escape(stringArray.join("")))
197
- }
198
-
199
- /**
200
- * Converts an Uint8Array containing UTF-8 string data into a string.
201
- *
202
- * @param uint8Array The Uint8Array.
203
- * @return The string.
204
- */
205
- export function utf8Uint8ArrayToString(uint8Array: Uint8Array): string {
206
- return decoder.decode(uint8Array)
207
- }
208
-
209
- export function hexToUint8Array(hex: Hex): Uint8Array {
210
- let bufView = new Uint8Array(hex.length / 2)
211
- for (let i = 0; i < bufView.byteLength; i++) {
212
- bufView[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16)
213
- }
214
- return bufView
215
- }
216
-
217
- const hexDigits = '0123456789abcdef'
218
-
219
- export function uint8ArrayToHex(uint8Array: Uint8Array): Hex {
220
- let hex = ""
221
- for (let i = 0; i < uint8Array.byteLength; i++) {
222
- let value = uint8Array[i]
223
- hex += hexDigits[value >> 4] + hexDigits[value & 15]
224
- }
225
- return hex
226
- }
227
-
228
- /**
229
- * Converts an Uint8Array to a Base64 encoded string.
230
- *
231
- * @param bytes The bytes to convert.
232
- * @return The Base64 encoded string.
233
- */
234
- export function uint8ArrayToBase64(bytes: Uint8Array): Base64 {
235
- if (bytes.length < 512) {
236
- // Apply fails on big arrays fairly often. We tried it with 60000 but if you're already
237
- // deep in the stack than we cannot allocate such a big argument array.
238
- return btoa(String.fromCharCode.apply(null, bytes))
239
- }
240
- let binary = ''
241
- const len = bytes.byteLength
242
- for (let i = 0; i < len; i++) {
243
- binary += String.fromCharCode(bytes[i])
244
- }
245
- return btoa(binary)
246
- }
247
-
248
- export function int8ArrayToBase64(bytes: Int8Array): Base64 {
249
- // Values 0 to 127 are the same for signed and unsigned bytes
250
- // and -128 to -1 are mapped to the same chars as 128 to 255.
251
- let converted = new Uint8Array(bytes)
252
- return uint8ArrayToBase64(converted)
253
- }
254
-
255
- /**
256
- * Converts a base64 encoded string to a Uint8Array.
257
- *
258
- * @param base64 The Base64 encoded string.
259
- * @return The bytes.
260
- */
261
- export function base64ToUint8Array(base64: Base64): Uint8Array {
262
- if (base64.length % 4 !== 0) {
263
- throw new Error(`invalid base64 length: ${base64} (${base64.length})`);
264
- }
265
- const binaryString = atob(base64)
266
- const result = new Uint8Array(binaryString.length)
267
- for (let i = 0; i < binaryString.length; i++) {
268
- result[i] = binaryString.charCodeAt(i)
269
- }
270
- return result
271
- }
272
-
273
- /**
274
- * Converts a Uint8Array containing string data into a string, given the charset the data is in.
275
- * @param charset The charset. Must be supported by TextDecoder.
276
- * @param bytes The string data
277
- * @trhows RangeError if the charset is not supported
278
- * @return The string
279
- */
280
- export function uint8ArrayToString(charset: string, bytes: Uint8Array): string {
281
- // $FlowExpectedError[incompatible-call] we will rely on the constructor throwing an error if the charset is not supported
282
- const decoder = new TextDecoder(charset)
283
- return decoder.decode(bytes);
284
- }
285
-
286
- /**
287
- * Decodes a quoted-printable piece of text in a given charset.
288
- * This was copied and modified from https://github.com/mathiasbynens/quoted-printable/blob/master/src/quoted-printable.js (MIT licensed)
289
- *
290
- * @param charset Must be supported by TextEncoder
291
- * @param input The encoded text
292
- * @throws RangeError if the charset is not supported
293
- * @returns The text as a JavaScript string
294
- */
295
- export function decodeQuotedPrintable(charset: string, input: string): string {
296
- return input
297
- // https://tools.ietf.org/html/rfc2045#section-6.7, rule 3:
298
- // “Therefore, when decoding a `Quoted-Printable` body, any trailing white
299
- // space on a line must be deleted, as it will necessarily have been added
300
- // by intermediate transport agents.”
301
- .replace(/[\t\x20]$/gm, '')
302
- // Remove hard line breaks preceded by `=`. Proper `Quoted-Printable`-
303
- // encoded data only contains CRLF line endings, but for compatibility
304
- // reasons we support separate CR and LF too.
305
- .replace(/=(?:\r\n?|\n|$)/g, '')
306
- // Decode escape sequences of the form `=XX` where `XX` is any
307
- // combination of two hexidecimal digits. For optimal compatibility,
308
- // lowercase hexadecimal digits are supported as well. See
309
- // https://tools.ietf.org/html/rfc2045#section-6.7, note 1.
310
- .replace(/(=([a-fA-F0-9]{2}))+/g,
311
- match => {
312
- const hexValues = match.split(/=/)
313
- // splitting on '=' is convenient, but adds an empty string at the start due to the first byte
314
- hexValues.shift()
315
- const intArray = hexValues.map(char => parseInt(char, 16))
316
- const bytes = Uint8Array.from(intArray)
317
- return uint8ArrayToString(charset, bytes)
318
- })
319
- }
320
-
321
- export function decodeBase64(charset: string, input: string): string {
322
- return uint8ArrayToString(charset, base64ToUint8Array(input))
323
- }
324
-
325
- export function stringToBase64(str: string): string {
326
- return uint8ArrayToBase64(stringToUtf8Uint8Array(str))
327
- }
328
-
329
-
package/lib/LazyLoaded.js DELETED
@@ -1,87 +0,0 @@
1
- // @flow
2
- import type {lazyAsync} from "./Utils"
3
- import {neverNull} from "./Utils"
4
-
5
- /**
6
- * A wrapper for an object that shall be lazy loaded asynchronously. If loading the object is triggered in parallel (getAsync()) the object is actually only loaded once but returned to all calls of getAsync().
7
- * If the object was loaded once it is not loaded again.
8
- */
9
- export class LazyLoaded<T> {
10
-
11
- _isLoaded: boolean
12
- _loadingPromise: ?Promise<T>; // null if loading is not started yet
13
- _loadedObject: ?T;
14
- _loadFunction: lazyAsync<T>;
15
-
16
- /**
17
- * @param loadFunction The function that actually loads the object as soon as getAsync() is called the first time.
18
- * @param defaultValue The value that shall be returned by getSync() or getLoaded() as long as the object is not loaded yet.
19
- */
20
- constructor(loadFunction: lazyAsync<T>, defaultValue: ?T) {
21
- this._isLoaded = false
22
- this._loadFunction = loadFunction
23
- this._loadingPromise = null
24
- this._loadedObject = defaultValue
25
- }
26
-
27
- load(): this {
28
- this.getAsync()
29
- return this
30
- }
31
-
32
- isLoaded(): boolean {
33
- return this._isLoaded
34
- }
35
-
36
- /**
37
- * Loads the object if it is not loaded yet. May be called in parallel and takes care that the load function is only called once.
38
- */
39
- getAsync(): Promise<T> {
40
- if (this.isLoaded()) {
41
- return Promise.resolve(neverNull(this._loadedObject))
42
- } else {
43
- if (!this._loadingPromise) {
44
- this._loadingPromise = this._loadFunction().then(result => {
45
- this._loadedObject = result
46
- this._isLoaded = true
47
- return result
48
- })
49
- }
50
- return this._loadingPromise
51
- }
52
- }
53
-
54
- /**
55
- * Returns null if the object is not loaded yet.
56
- */
57
- getSync(): ?T {
58
- return this._loadedObject
59
- }
60
-
61
- /**
62
- * Only call this function if you know that the object is already loaded.
63
- */
64
- getLoaded(): T {
65
- return neverNull(this._loadedObject)
66
- }
67
-
68
- /**
69
- * Removes the currently loaded object, so it will be loaded again with the next getAsync() call. Does not set any default value.
70
- */
71
- reset() {
72
- this._isLoaded = false
73
- this._loadingPromise = null
74
- this._loadedObject = null
75
- }
76
-
77
- /**
78
- * Loads the object again and replaces the current one
79
- */
80
- reload(): Promise<T> {
81
- return this._loadFunction().then(result => {
82
- this._isLoaded = true
83
- this._loadedObject = result
84
- return result
85
- })
86
- }
87
- }
package/lib/MapUtils.js DELETED
@@ -1,42 +0,0 @@
1
- //@flow
2
- import {neverNull} from "./Utils"
3
-
4
- /**
5
- * Merges multiple maps into a single map with lists of values.
6
- * @param maps
7
- */
8
- export function mergeMaps<T>(maps: Map<string, T>[]): Map<string, T[]> {
9
- return maps.reduce((mergedMap: Map<string, T[]>, map: Map<string, T>) => { // merge same key of multiple attributes
10
- map.forEach((value: T, key: string) => {
11
- if (mergedMap.has(key)) {
12
- neverNull(mergedMap.get(key)).push(value)
13
- } else {
14
- mergedMap.set(key, [value])
15
- }
16
- })
17
- return mergedMap
18
- }, new Map())
19
- }
20
-
21
- export function getFromMap<K, V>(map: Map<K, V>, key: K, byDefault: () => V): V {
22
- let value = map.get(key)
23
- if (!value) {
24
- value = byDefault()
25
- map.set(key, value)
26
- }
27
-
28
- return value
29
- }
30
-
31
- /** Creates a new map with key and value added to {@param map}. It is like set() but for immutable map. */
32
- export function addMapEntry<K, V>(map: $ReadOnlyMap<K, V>, key: K, value: V): Map<K, V> {
33
- const newMap = new Map(map)
34
- newMap.set(key, value)
35
- return newMap
36
- }
37
-
38
- export function deleteMapEntry<K, V>(map: $ReadOnlyMap<K, V>, key: K): Map<K, V> {
39
- const newMap = new Map(map)
40
- newMap.delete(key)
41
- return newMap
42
- }
package/lib/MathUtils.js DELETED
@@ -1,12 +0,0 @@
1
- // @flow
2
-
3
- export function mod(n: number, m: number): number {
4
- return ((n % m) + m) % m;
5
- }
6
-
7
- /**
8
- * Clamp value to between min and max (inclusive)
9
- */
10
- export function clamp(value: number, min: number, max: number): number {
11
- return Math.max(min, Math.min(value, max))
12
- }
package/lib/PromiseMap.js DELETED
@@ -1,121 +0,0 @@
1
- // @flow
2
-
3
- /**
4
- * @file Vendored version of p-map: https://github.com/sindresorhus/p-map/
5
- * Vendored to avoid having dependency on AggregateError.
6
- *
7
- * Changed: default concurrency level is 1 and not Infinite
8
- */
9
-
10
- export interface Options {
11
- /**
12
- Number of concurrently pending promises returned by `mapper`.
13
- Must be an integer from 1 and up or `Infinity`.
14
- @default 1
15
- */
16
- +concurrency?: number;
17
- }
18
-
19
- /**
20
- Function which is called for every item in `input`. Expected to return a `Promise` or value.
21
- @param element - Iterated element.
22
- @param index - Index of the element in the source array.
23
- */
24
- export type Mapper<Element, NewElement> = (
25
- element: Element,
26
- index: number
27
- ) => Promise<NewElement> | NewElement;
28
-
29
- /**
30
- @param iterable - Iterated over concurrently in the `mapper` function.
31
- @param mapper - Function which is called for every item in `input`. Expected to return a `Promise` or value.
32
- @param options
33
- @returns A `Promise` that is fulfilled when all promises in `input` and ones returned from `mapper` are fulfilled, or rejects if any of the promises reject. The fulfilled value is an `Array` of the fulfilled values returned from `mapper` in `input` order.
34
- @example
35
- ```
36
- import pMap from 'p-map';
37
- import got from 'got';
38
- const sites = [
39
- getWebsiteFromUsername('sindresorhus'), //=> Promise
40
- 'https://avajs.dev',
41
- 'https://github.com'
42
- ];
43
- const mapper = async site => {
44
- const {requestUrl} = await got.head(site);
45
- return requestUrl;
46
- };
47
- const result = await pMap(sites, mapper, {concurrency: 2});
48
- console.log(result);
49
- //=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
50
- ```
51
- */
52
- export async function pMap<Element, NewElement>(
53
- iterable: Iterable<Element>,
54
- mapper: Mapper<Element, NewElement>,
55
- options: Options = {},
56
- ): Promise<Array<NewElement>> {
57
- const {
58
- concurrency = 1,
59
- } = options
60
- return new Promise((resolve, reject) => {
61
- if (typeof mapper !== 'function') {
62
- throw new TypeError('Mapper function is required');
63
- }
64
-
65
- if (!((Number.isSafeInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency >= 1)) {
66
- throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
67
- }
68
-
69
- const result = [];
70
- const errors = [];
71
- // $FlowIssue[incompatible-use]
72
- const iterator = iterable[Symbol.iterator]();
73
- let isRejected = false;
74
- let isIterableDone = false;
75
- let resolvingCount = 0;
76
- let currentIndex = 0;
77
-
78
- const next = () => {
79
- if (isRejected) {
80
- return;
81
- }
82
-
83
- const nextItem = iterator.next();
84
- const index = currentIndex;
85
- currentIndex++;
86
-
87
- if (nextItem.done) {
88
- isIterableDone = true;
89
-
90
- if (resolvingCount === 0) {
91
- resolve(result);
92
- }
93
-
94
- return;
95
- }
96
-
97
- resolvingCount++;
98
-
99
- (async () => {
100
- try {
101
- const element = await nextItem.value;
102
- result[index] = await mapper(element, index);
103
- resolvingCount--;
104
- next();
105
- } catch (error) {
106
- isRejected = true;
107
- reject(error);
108
- }
109
- })();
110
- };
111
-
112
- for (let index = 0; index < concurrency; index++) {
113
- next();
114
-
115
- if (isIterableDone) {
116
- break;
117
- }
118
- }
119
- });
120
- }
121
-