forked from pybricks/pybricks-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
57 lines (49 loc) · 1.7 KB
/
index.ts
File metadata and controls
57 lines (49 loc) · 1.7 KB
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2022-2023 The Pybricks Authors
import {
FirmwareMetadata,
FirmwareMetadataV110,
FirmwareMetadataV200,
HubType,
} from '@pybricks/firmware';
import * as semver from 'semver';
const encoder = new TextEncoder();
/**
* Validates the hub name.
* @param hubName The hub name.
* @param metadata The firmware metadata.
* @returns True if the name if valid, otherwise false.
*/
export function validateHubName(hubName: string, metadata: FirmwareMetadata): boolean {
const encoded = encoder.encode(hubName);
if (semver.satisfies(metadata['metadata-version'], '^1.1')) {
return encoded.length < (metadata as FirmwareMetadataV110)['max-hub-name-size'];
}
if (semver.satisfies(metadata['metadata-version'], '^2.0')) {
return encoded.length < (metadata as FirmwareMetadataV200)['hub-name-size'];
}
return false;
}
const supportHubs: readonly HubType[] = [
HubType.MoveHub,
HubType.CityHub,
HubType.TechnicHub,
HubType.PrimeHub,
HubType.EssentialHub,
HubType.EV3,
];
export function validateMetadata(metadata: FirmwareMetadata) {
if (semver.satisfies(metadata['metadata-version'], '^1')) {
if (!supportHubs.includes(metadata['device-id'])) {
throw new Error(`"unsupported "device-id": ${metadata['device-id']}`);
}
} else if (semver.satisfies(metadata['metadata-version'], '^2')) {
if (!supportHubs.includes(metadata['device-id'])) {
throw new Error(`"unsupported "device-id": ${metadata['device-id']}`);
}
} else {
throw new Error(
`unsupported "metadata-version": "${metadata['metadata-version']}"`,
);
}
}