• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

box / box-typescript-sdk-gen / 16145759281

08 Jul 2025 02:14PM UTC coverage: 42.108% (+0.06%) from 42.048%
16145759281

Pull #659

github

web-flow
Merge 048f2ffab into cb0c35df4
Pull Request #659: test: Improve names in transfer integration test (box/box-codegen#759)

4375 of 18050 branches covered (24.24%)

Branch coverage included in aggregate %.

16066 of 30494 relevant lines covered (52.69%)

145.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.06
/src/internal/utils.ts
1
import { v4 as uuidv4 } from 'uuid';
234✔
2
import {
234✔
3
  calculateMD5Hash,
4
  compareSignatures,
5
  computeWebhookSignature,
6
  createAgent,
7
  createJwtAssertion,
8
  decodeBase64ByteStream,
9
  generateByteBuffer,
10
  generateByteStreamFromBuffer,
11
  Hash,
12
  iterateChunks,
13
  jsonStringifyWithEscapedUnicode,
14
  JwtAlgorithm,
15
  JwtKey,
16
  JwtSignOptions,
17
  readByteStream,
18
  readTextFromFile,
19
  stringToByteStream,
20
  ByteStream,
21
  Buffer,
22
  FormData,
23
  generateReadableStreamFromFile,
24
  getEnvVar,
25
  setEnvVar,
26
  utilLib,
27
  PrivateKeyDecryptor,
28
  DefaultPrivateKeyDecryptor,
29
} from './utilsNode';
30
import { MultipartItem } from '../networking';
31
import { sanitizedValue } from '../serialization/json';
234✔
32

33
export type HashName = 'sha1';
34
export type DigestHashType = 'base64';
35

36
export type { JwtKey, JwtAlgorithm, JwtSignOptions, ByteStream };
37
export type { PrivateKeyDecryptor };
38

39
export {
40
  Hash,
270✔
41
  generateByteBuffer,
255✔
42
  generateByteStreamFromBuffer,
5,030✔
43
  decodeBase64ByteStream,
237✔
44
  stringToByteStream,
243✔
45
  generateReadableStreamFromFile,
234✔
46
  readByteStream,
498✔
47
  iterateChunks,
243✔
48
  createJwtAssertion,
652✔
49
  readTextFromFile,
234✔
50
  createAgent,
40,282✔
51
  jsonStringifyWithEscapedUnicode,
234✔
52
  compareSignatures,
309✔
53
  computeWebhookSignature,
333✔
54
  calculateMD5Hash,
423✔
55
  getEnvVar,
940✔
56
  setEnvVar,
234✔
57
  utilLib,
468✔
58
  DefaultPrivateKeyDecryptor,
1,164✔
59
};
60

61
export { Buffer, FormData };
423✔
62
export type { CancellationController, CancellationToken };
63
export type Iterator<T = any> = AsyncIterator<T>;
64
export type AgentOptions = any;
65
export type Agent = any;
66

67
export function isBrowser() {
234✔
68
  return (
7,285✔
69
    typeof window === 'object' && typeof document === 'object' && window.crypto
7,285!
70
  );
71
}
72

73
export function getUuid() {
234✔
74
  return uuidv4();
944✔
75
}
76

77
export function decodeBase64(value: string) {
234✔
78
  return Buffer.from(value, 'base64').toString('utf8');
424✔
79
}
80

81
export function hexToBase64(data: string): string {
234✔
82
  return Buffer.from(data, 'hex').toString('base64');
27✔
83
}
84

85
// using wrappers for date/datetime because of inability to export built-in Date types
86
class DateWrapper {
87
  constructor(public readonly value: Date) {}
41✔
88
}
89

90
class DateTimeWrapper {
91
  constructor(public readonly value: Date) {}
8,745✔
92
}
93

94
export { DateWrapper as Date, DateTimeWrapper as DateTime };
234✔
95

96
export function dateFromString(value: string): DateWrapper {
234✔
97
  return new DateWrapper(new Date(value));
41✔
98
}
99

100
export function dateToString(date: DateWrapper): string {
234✔
101
  return date.value.toISOString().match(/^\d{4}-\d{2}-\d{2}/)![0];
6✔
102
}
103

104
export function dateTimeFromString(value: string): DateTimeWrapper {
234✔
105
  return new DateTimeWrapper(new Date(value));
8,730✔
106
}
107

108
export function dateTimeToString(dateTime: DateTimeWrapper): string {
234✔
109
  return (
63✔
110
    dateTime.value
111
      .toISOString()
112
      .match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)![0] + '+00:00'
113
  );
114
}
115

116
export function epochSecondsToDateTime(seconds: number): DateTimeWrapper {
234✔
117
  return new DateTimeWrapper(new Date(seconds * 1000));
15✔
118
}
119

120
export function dateTimeToEpochSeconds(dateTime: DateTimeWrapper): number {
234✔
121
  return Math.floor(dateTime.value.getTime() / 1000);
60✔
122
}
123

124
export {
125
  dateToString as serializeDate,
234✔
126
  dateFromString as deserializeDate,
234✔
127
  dateTimeToString as serializeDateTime,
234✔
128
  dateTimeFromString as deserializeDateTime,
234✔
129
};
130

131
// Function to convert a hexadecimal string to base64
132
export function hexStrToBase64(hex: string) {
234✔
133
  const hexString = hex.toString(); // Ensure the input is a string
×
134
  const hexBytes = new Uint8Array(hexString.length / 2);
×
135

136
  // Convert the hexadecimal string to bytes
137
  for (let i = 0; i < hexString.length; i += 2) {
×
138
    hexBytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
×
139
  }
140

141
  // Encode the bytes as base64
142
  const base64 = btoa(String.fromCharCode.apply(null, Array.from(hexBytes)));
×
143

144
  return base64;
×
145
}
146

147
export function generateByteStream(size: number): ByteStream {
234✔
148
  return generateByteStreamFromBuffer(generateByteBuffer(size));
174✔
149
}
150

151
export function bufferEquals(buffer1: Buffer, buffer2: Buffer): boolean {
234✔
152
  return Buffer.compare(buffer1, buffer2) === 0;
21✔
153
}
154

155
export function bufferLength(buffer: Buffer): number {
234✔
156
  return buffer.length;
27✔
157
}
158

159
export async function reduceIterator<T, U>(
234✔
160
  iterator: Iterator<T>,
161
  reducer: (accumulator: U, current: T) => Promise<U>,
162
  initialValue: U,
163
): Promise<U> {
164
  let result = initialValue;
9✔
165
  let iteration = await iterator.next();
9✔
166

167
  while (!iteration.done) {
9✔
168
    result = await reducer(result, iteration.value);
27✔
169
    iteration = await iterator.next();
27✔
170
  }
171

172
  return result;
9✔
173
}
174

175
export function prepareParams(map: {
234✔
176
  readonly [key: string]: undefined | string;
177
}): { readonly [key: string]: string } {
178
  if (!map || typeof map !== 'object') {
3,767!
179
    throw new Error('Expecting obj to be an object in prepareParams');
×
180
  }
181
  return Object.fromEntries(
3,767✔
182
    Object.entries(map).filter<[string, string]>(
183
      (entry): entry is [string, string] => typeof entry[1] === 'string',
3,032✔
184
    ),
185
  );
186
}
187

188
export function toString(value: any): string {
234✔
189
  if (typeof value === 'string' || value == null) {
4,371✔
190
    return value;
4,191✔
191
  }
192
  return String(value);
180✔
193
}
194

195
type CancellationController = AbortController;
196
type CancellationToken = AbortSignal;
197

198
/**
199
 * Creates a cancellation token that will be cancelled after a given delay in ms.
200
 *
201
 * @param {number} delay Delay in ms.
202
 * @returns {CancellationToken} Cancellation token.
203
 */
204
export function createTokenAndCancelAfter(delay: number): CancellationToken {
234✔
205
  return AbortSignal.timeout(delay);
3✔
206
}
207

208
/**
209
 * Get current epoch time in seconds.
210
 */
211
export function getEpochTimeInSeconds(): number {
234✔
212
  return Math.floor(Date.now() / 1000);
466✔
213
}
214

215
export async function delayInSeconds(seconds: number): Promise<void> {
234✔
216
  return await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
12✔
217
}
218

219
/**
220
 * Get value from object raw data.
221
 *
222
 * @param obj Object with raw data from which to get the value.
223
 * @param key Key of the value to get.
224
 * @returns Value from object raw data.
225
 */
226
export function getValueFromObjectRawData(obj: any, key: string): any {
234✔
227
  if (!obj || typeof obj !== 'object' || !obj.rawData) {
30!
228
    return undefined;
×
229
  }
230
  return key.split('.').reduce((value, k) => value?.[k], obj.rawData);
60!
231
}
232

233
/**
234
 * Create a null value.
235
 *
236
 * @returns null
237
 */
238
export function createNull(): null {
234✔
239
  return null;
15✔
240
}
241

242
/**
243
 * Create a cancellation controller.
244
 */
245
export function createCancellationController(): CancellationController {
234✔
246
  return new AbortController();
6✔
247
}
248

249
export function random(min: number, max: number): number {
234✔
250
  return Math.random() * (max - min) + min;
×
251
}
252

253
export async function multipartStreamToBuffer(
234✔
254
  multipart: readonly MultipartItem[],
255
): Promise<(MultipartItem & { fileStreamBuffer?: Buffer })[]> {
256
  return await Promise.all(
189✔
257
    multipart.map(async (item) => {
375✔
258
      if (!item.fileStream) {
375✔
259
        return item;
186✔
260
      }
261
      return {
189✔
262
        ...item,
263
        fileStream: undefined,
264
        fileStreamBuffer: item.fileStream
189!
265
          ? await readByteStream(item.fileStream)
266
          : undefined,
267
      };
268
    }),
269
  );
270
}
271

272
export function multipartBufferToStream(
234✔
273
  multipart: (MultipartItem & { fileStreamBuffer?: Buffer })[],
274
): readonly MultipartItem[] {
275
  return multipart.map((item) => {
189✔
276
    if (!item.fileStreamBuffer) {
375✔
277
      return item;
186✔
278
    }
279
    return {
189✔
280
      ...item,
281
      fileStreamBuffer: undefined,
282
      fileStream: item.fileStreamBuffer
189!
283
        ? generateByteStreamFromBuffer(item.fileStreamBuffer)
284
        : undefined,
285
    } as MultipartItem;
286
  });
287
}
288

289
/**
290
 * Sanitize a map by replacing sensitive values with a placeholder.
291
 * @param dictionary The map to sanitize
292
 * @param keysToSanitize Keys to sanitize
293
 */
294
export function sanitizeMap(
234✔
295
  dictionary: Record<string, string>,
296
  keysToSanitize: Record<string, string>,
297
): Record<string, string> {
298
  return Object.fromEntries(
2✔
299
    Object.entries(dictionary).map(([k, v]) =>
300
      k.toLowerCase() in keysToSanitize ? [k, sanitizedValue()] : [k, v],
21✔
301
    ),
302
  );
303
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc