/
ProjectConfiguration.ts
654 lines (580 loc) · 18.7 KB
/
ProjectConfiguration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import humanizeList from 'humanize-list';
import validator from 'validator';
import lodash from 'lodash';
import semver from 'semver';
import buildTargets from './buildTargets';
import DiagnosticList from './DiagnosticList';
import { validateLanguageTag } from './languageTag';
import sdkVersion from './sdkVersion';
const knownBuildTargets = Object.keys(buildTargets);
export enum AppType {
APP = 'app',
CLOCKFACE = 'clockface',
SERVICE = 'service',
}
export const VALID_APP_TYPES = Object.values(AppType);
export const MAX_LENGTH_APP_CLUSTER_ID = 64;
const MIN_COMPANION_DEFAULT_WAKE_INTERVAL_MS = 300000;
export type LocalesConfig = { [locale: string]: { name: string } };
export interface BaseProjectConfiguration {
appType: AppType;
appDisplayName: string;
appUUID: string;
requestedPermissions: string[];
i18n: LocalesConfig;
defaultLanguage: string;
buildTargets: string[];
// We don't want to accidentally serialize `enableProposedAPI: false`
// out to users' package.json files.
enableProposedAPI?: true;
appClusterID?: string[];
developerID?: string;
companionDefaultWakeInterval?: number;
}
export interface AppProjectConfiguration extends BaseProjectConfiguration {
appType: AppType.APP;
wipeColor: string;
iconFile: string;
}
export interface ClockProjectConfiguration extends BaseProjectConfiguration {
appType: AppType.CLOCKFACE;
}
export interface ServiceProjectConfiguration extends BaseProjectConfiguration {
appType: AppType.SERVICE;
}
type ProjectConfiguration =
| AppProjectConfiguration
| ClockProjectConfiguration
| ServiceProjectConfiguration;
export default ProjectConfiguration;
export const MAX_DISPLAY_NAME_LENGTH = 30;
export enum Locales {
'en-US' = 'English (US)',
'de-DE' = 'German',
'es-ES' = 'Spanish',
'fr-FR' = 'French',
'it-IT' = 'Italian',
'ja-JP' = 'Japanese',
'ko-KR' = 'Korean',
'nl-NL' = 'Dutch',
'sv-SE' = 'Swedish',
'zh-CN' = 'Chinese (Simplified)',
'zh-TW' = 'Chinese (Traditional)',
'pt-BR' = 'Portuguese (Brazillian)',
'id-ID' = 'Indonesian (Bahasa)',
'ro-RO' = 'Romanian',
'ru-RU' = 'Russian',
'pl-PL' = 'Polish',
'cs-CZ' = 'Czech',
'nb-NO' = 'Norwegian (Bokmål)',
}
const languageTags = Object.keys(Locales);
export enum Permission {
ACCESS_ACTIVITY = 'access_activity',
ACCESS_AOD = 'access_aod',
ACCESS_APP_CLUSTER_STORAGE = 'access_app_cluster_storage',
ACCESS_CALENDAR = 'access_calendar',
ACCESS_EXERCISE = 'access_exercise',
ACCESS_HEART_RATE = 'access_heart_rate',
ACCESS_INTERNET = 'access_internet',
ACCESS_LOCATION = 'access_location',
ACCESS_SECURE_EXCHANGE = 'access_secure_exchange',
ACCESS_SLEEP = 'access_sleep',
ACCESS_USER_PROFILE = 'access_user_profile',
DIAGNOSTIC_INFO = 'diagnostic_info',
FITBIT_INTERNAL = 'fitbit_internal',
FITBIT_TOKEN = 'fitbit_token',
RUN_BACKGROUND = 'run_background',
EXTERNAL_APP_COMMUNICATION = 'external_app_communication',
MOBILE_NOTIFICATIONS = 'mobile_notifications',
DEVICE_NOTIFICATIONS = 'device_notifications',
}
const permissionTypes = [
{
key: Permission.ACCESS_ACTIVITY,
name: 'Activity',
// tslint:disable-next-line:max-line-length
description:
'Read user activities for today (distance, calories, steps, elevation and active minutes), and daily goals',
},
{
key: Permission.ACCESS_USER_PROFILE,
name: 'User Profile',
// tslint:disable-next-line:max-line-length
description:
'Read non-identifiable personal information (gender, age, height, weight, resting HR, basal metabolic rate, stride, HR zones)',
},
{
key: Permission.ACCESS_HEART_RATE,
name: 'Heart Rate',
description: 'Application may read the heart-rate sensor in real-time',
},
{
key: Permission.ACCESS_LOCATION,
name: 'Location',
description: 'Application and companion may use GPS',
},
{
key: Permission.ACCESS_INTERNET,
name: 'Internet',
description:
'Companion may communicate with the Internet using your phone data connection',
},
{
key: Permission.RUN_BACKGROUND,
name: 'Run in background',
description:
'Companion may run even when the application is not actively in use',
},
{
key: Permission.ACCESS_EXERCISE,
name: 'Exercise Tracking',
description: 'Application may track an exercise',
sdkVersion: '>=3.0.0',
},
{
key: Permission.ACCESS_APP_CLUSTER_STORAGE,
name: 'App Cluster Storage',
description:
'Application may access storage shared by other applications from the same developer',
sdkVersion: '>=4.0.0',
},
{
key: Permission.ACCESS_CALENDAR,
name: 'Calendars',
description:
'Application may access calendar data stored on the mobile device',
sdkVersion: '>=4.1.0',
},
{
key: Permission.ACCESS_SLEEP,
name: 'Sleep',
description: 'Application may detect whether the user is sleeping or not',
sdkVersion: '>=4.2.0',
},
];
const restrictedPermissionTypes = [
{
key: Permission.FITBIT_TOKEN,
name: '[Restricted] Fitbit Token',
description: 'Access Fitbit API token',
},
{
key: Permission.EXTERNAL_APP_COMMUNICATION,
name: '[Restricted] External Application Communication',
description:
'Allows communication between external mobile applications and companion',
},
{
key: Permission.ACCESS_SECURE_EXCHANGE,
name: '[Restricted] Secure Exchange',
description: 'Allows securing any data and verifying that data was secured',
},
{
key: Permission.ACCESS_AOD,
name: '[Restricted] Always-on Display',
description:
'Application may stay active whilst always-on display mode is active',
sdkVersion: '>=4.1.0',
},
{
key: Permission.MOBILE_NOTIFICATIONS,
name: '[Restricted] Mobile Notifications',
description: 'Application may display notifications on the mobile device',
sdkVersion: '>=4.1.0',
},
{
key: Permission.DIAGNOSTIC_INFO,
name: '[Restricted] Diagnostic Info',
description: 'Collect usage info e.g. error logs for investigation',
},
{
key: Permission.DEVICE_NOTIFICATIONS,
name: '[Restricted] Device Notifications',
description: 'Application may display notifications on the watch',
sdkVersion: '>=6.0.0',
},
{
key: Permission.FITBIT_INTERNAL,
name: '[Restricted] Fitbit Internal',
description: 'Access Fitbit Internal APIs',
},
];
export function getAllPermissionTypes(options: {
enableProposedAPI?: boolean;
includeRestrictedPermissions?: boolean;
}) {
const { enableProposedAPI, includeRestrictedPermissions } = {
enableProposedAPI: false,
includeRestrictedPermissions: true,
...options,
};
return [
...permissionTypes,
...(includeRestrictedPermissions ? restrictedPermissionTypes : []),
].filter(
(permission) =>
!permission.sdkVersion ||
semver.satisfies(sdkVersion(), permission.sdkVersion) ||
enableProposedAPI,
);
}
function constrainedSetDiagnostics({
actualValues,
knownValues,
valueTypeNoun,
notFoundIsFatal = false,
}: {
actualValues: ReadonlyArray<any>;
knownValues: ReadonlyArray<any>;
valueTypeNoun: string;
notFoundIsFatal?: boolean;
}) {
const unknownValues = lodash.without(actualValues, ...knownValues);
const diagnostics = new DiagnosticList();
if (unknownValues.length > 0) {
const unknownValueStrings = unknownValues.filter(lodash.isString);
const unknownValueOther = lodash
.without(unknownValues, ...unknownValueStrings)
.map(String);
if (unknownValueStrings.length) {
const errStr = `One or more ${valueTypeNoun} was invalid: ${unknownValueStrings.join(
', ',
)}`;
if (notFoundIsFatal) diagnostics.pushFatalError(errStr);
else diagnostics.pushWarning(errStr);
}
if (unknownValueOther.length) {
diagnostics.pushFatalError(
`One or more ${valueTypeNoun} was not a string: ${unknownValueOther.join(
', ',
)}`,
);
}
}
const duplicatedValues = lodash
.uniq(actualValues)
.filter(
(value) =>
actualValues.indexOf(value) !== actualValues.lastIndexOf(value),
);
if (duplicatedValues.length > 0) {
diagnostics.pushWarning(
`One or more ${valueTypeNoun} was specified multiple times: ${duplicatedValues.join(
', ',
)}`,
);
}
return diagnostics;
}
function normalizeLanguageTag(languageTag: string) {
const match = /^([a-z]{2})(-[a-z]{2})?$/i.exec(languageTag);
if (match === null) return languageTag;
const [, language, region] = match;
return language.toLowerCase() + (region || '').toUpperCase();
}
export function normalizeLocales(locales: LocalesConfig) {
/**
* FbOS 3.0 has a max size limit on the app manifest of 1K
* so if a developer specifies language + locale variants (eg en and en-US)
* for all languages they'll quickly exceed this. This code merges the language
* tag into a locale tag unless one is present.
*/
const localeMapping: Record<string, string | undefined> = lodash.mapKeys(
Object.keys(Locales),
(tag) => tag.split('-')[0],
);
const normalizedLocales: LocalesConfig = {};
for (const [locale, localeConfig] of Object.entries(locales)) {
const mappedLocale = localeMapping[locale];
// If no mapping exists, just normalize + copy
if (mappedLocale === undefined) {
normalizedLocales[normalizeLanguageTag(locale)] = localeConfig;
continue;
}
// If a mapping exists, but locale info for the mapped locale already exists
// do nothing.
if (locales[mappedLocale] !== undefined) {
continue;
}
// If a mapping exists and won't overwrite, just copy
normalizedLocales[mappedLocale] = localeConfig;
}
return normalizedLocales;
}
/**
* Normalize the project configuration from a parsed package.json.
*
* @param config Configuration object
* @param defaults Override the default values to use
*/
export function normalizeProjectConfig(
config: any,
defaults?: Partial<ProjectConfiguration>,
): ProjectConfiguration {
if (!lodash.isPlainObject(config)) {
throw new TypeError('Project configuration root must be an object');
}
const mergedConfig: ProjectConfiguration = {
// The *cough* default defaults
appUUID: '',
appType: AppType.APP,
appDisplayName: '',
iconFile: 'resources/icon.png',
wipeColor: '',
requestedPermissions: [],
buildTargets: [],
i18n: {},
defaultLanguage: 'en-US',
// Override defaults
...defaults,
// The config object proper
...(config.fitbit as {}),
};
const { requestedPermissions } = mergedConfig;
if (!Array.isArray(requestedPermissions)) {
// tslint:disable-next-line:max-line-length
throw new TypeError(
`fitbit.requestedPermissions must be an array, not ${typeof requestedPermissions}`,
);
}
mergedConfig.i18n = normalizeLocales(mergedConfig.i18n);
if (typeof mergedConfig.appClusterID === 'string') {
mergedConfig.appClusterID = [mergedConfig.appClusterID];
} else if (
!Array.isArray(mergedConfig.appClusterID) &&
config.appClusterID !== undefined
) {
throw new TypeError(
`App Cluster ID field has unknown type ${typeof config.appClusterID}`,
);
}
return mergedConfig;
}
export function validateAppType(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
if (VALID_APP_TYPES.indexOf(config.appType) === -1) {
const appTypeNames = humanizeList(VALID_APP_TYPES, { conjunction: 'or' });
diagnostics.pushFatalError(
`App type '${config.appType}' is invalid, expected ${appTypeNames}`,
);
}
return diagnostics;
}
export function validateDisplayName(name: string) {
if (name.length === 0) {
return 'Display name must not be blank';
}
if (name.length > MAX_DISPLAY_NAME_LENGTH) {
return `Display name must not exceed ${MAX_DISPLAY_NAME_LENGTH} characters`;
}
return true;
}
export function validateProjectDisplayName(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
const result = validateDisplayName(config.appDisplayName);
if (result !== true) {
diagnostics.pushFatalError(result);
}
return diagnostics;
}
export function validateWipeColor(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
if (
config.appType === AppType.APP &&
!validator.isHexColor(config.wipeColor)
) {
diagnostics.pushFatalError('Wipe color must be a valid hex color');
}
return diagnostics;
}
export function validateRequestedPermissions({
enableProposedAPI,
requestedPermissions,
}: ProjectConfiguration) {
return constrainedSetDiagnostics({
actualValues: requestedPermissions,
knownValues: getAllPermissionTypes({
enableProposedAPI: !!enableProposedAPI,
}).map((permission) => permission.key),
valueTypeNoun: 'requested permissions',
notFoundIsFatal: false,
});
}
export function validateBuildTarget(
{ buildTargets }: ProjectConfiguration,
{ hasNativeComponents }: { hasNativeComponents: boolean },
) {
const diagnostics = constrainedSetDiagnostics({
actualValues: buildTargets,
knownValues: knownBuildTargets,
valueTypeNoun: 'build targets',
notFoundIsFatal: true,
});
if (
(buildTargets === undefined || buildTargets.length === 0) &&
!hasNativeComponents
) {
diagnostics.pushFatalError('At least one build target must be enabled');
}
return diagnostics;
}
export function validateLocaleDisplayName(
{ i18n }: ProjectConfiguration,
localeKey: keyof typeof Locales,
) {
const diagnostics = new DiagnosticList();
const locale = i18n[localeKey];
if (!locale) return diagnostics;
if (!locale.name || locale.name.length === 0) {
// tslint:disable-next-line:max-line-length
diagnostics.pushFatalError(
`Localized display name for ${Locales[localeKey]} must not be blank`,
);
}
if (locale.name.length > MAX_DISPLAY_NAME_LENGTH) {
// tslint:disable-next-line:max-line-length
diagnostics.pushFatalError(
`Localized display name for ${Locales[localeKey]} must not exceed ${MAX_DISPLAY_NAME_LENGTH} characters`,
);
}
return diagnostics;
}
export function validateLocaleDisplayNames(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
for (const localeKey of Object.keys(Locales)) {
diagnostics.extend(
validateLocaleDisplayName(config, localeKey as keyof typeof Locales),
);
}
return diagnostics;
}
export function validateSupportedLocales({ i18n }: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
const unknownLocales = lodash.without(
Object.keys(i18n),
...Object.keys(Locales),
);
if (unknownLocales.length > 0) {
diagnostics.pushWarning(`Invalid locales: ${unknownLocales.join(', ')}`);
}
return diagnostics;
}
export function validateAppUUID({ appUUID }: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
if (!validator.isUUID(String(appUUID))) {
diagnostics.pushFatalError(
'appUUID must be a valid UUID, run "npx fitbit-build generate-appid" to fix',
);
}
return diagnostics;
}
export function validateDefaultLanguage(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
if (!validateLanguageTag(config.defaultLanguage)) {
diagnostics.pushFatalError(
`Default language is an invalid language tag: ${
config.defaultLanguage
}. Must be ${humanizeList(languageTags, { conjunction: 'or' })}.`,
);
}
return diagnostics;
}
function validateClusterID(clusterID: string): string | undefined {
if (clusterID.length < 1 || clusterID.length > MAX_LENGTH_APP_CLUSTER_ID) {
return 'must be between 1-64 characters';
}
if (!/^([a-z0-9]+)(\.[a-z0-9]+)*$/.test(clusterID)) {
return 'may only contain alphanumeric characters separated by periods, eg: my.app.123';
}
}
// tslint:disable-next-line:cognitive-complexity
export function validateStorageGroup(config: ProjectConfiguration) {
const diagnostics = new DiagnosticList();
const enableProposedAPI = !!config.enableProposedAPI;
const hasRequestedPermission = getAllPermissionTypes({ enableProposedAPI })
.map((permission) => permission.key)
.filter((permission) =>
(config.requestedPermissions || []).includes(permission),
)
.includes(Permission.ACCESS_APP_CLUSTER_STORAGE);
if (hasRequestedPermission) {
if (config.appClusterID === undefined) {
diagnostics.pushFatalError(
'App Cluster ID must be set when the App Cluster Storage permission is requested',
);
// TODO: Tie this to future SDK version once known
} else if (config.appClusterID.length > 1 && !enableProposedAPI) {
diagnostics.pushFatalError(
`Only a single App Cluster ID may be declared`,
);
} else {
for (const clusterID of config.appClusterID) {
const validationError = validateClusterID(clusterID);
if (validationError) {
diagnostics.pushFatalError(
`App Cluster ID '${clusterID}' ${validationError}`,
);
}
}
}
if (config.developerID === undefined) {
diagnostics.pushFatalError(
'Developer ID must be set when the App Cluster Storage permission is requested',
);
} else if (!validator.isUUID(String(config.developerID))) {
diagnostics.pushFatalError('Developer ID must be a valid UUID');
}
} else if (
config.appClusterID !== undefined ||
config.developerID !== undefined
) {
diagnostics.pushFatalError(
'App Cluster Storage permission must be requested to set App Cluster ID and Developer ID fields',
);
}
return diagnostics;
}
export function validateCompanionDefaultWakeInterval(
config: ProjectConfiguration,
) {
const diagnostics = new DiagnosticList();
if (
typeof config.companionDefaultWakeInterval !== 'undefined' &&
(!Number.isInteger(config.companionDefaultWakeInterval) ||
config.companionDefaultWakeInterval <
MIN_COMPANION_DEFAULT_WAKE_INTERVAL_MS)
) {
diagnostics.pushFatalError(
`Default companion wake interval must be an integer value greater than or equal to ${MIN_COMPANION_DEFAULT_WAKE_INTERVAL_MS}`,
);
}
return diagnostics;
}
interface ValidationOptions {
hasNativeComponents?: boolean;
}
export function validate(
config: ProjectConfiguration,
options?: ValidationOptions,
) {
const { hasNativeComponents } = {
hasNativeComponents: false,
...options,
};
const diagnostics = new DiagnosticList();
[
validateAppUUID,
validateProjectDisplayName,
validateAppType,
validateWipeColor,
validateRequestedPermissions,
validateSupportedLocales,
validateLocaleDisplayNames,
validateDefaultLanguage,
validateStorageGroup,
validateCompanionDefaultWakeInterval,
].forEach((validator) => diagnostics.extend(validator(config)));
diagnostics.extend(validateBuildTarget(config, { hasNativeComponents }));
return diagnostics;
}