mirror of
https://github.com/Start9Labs/start-os.git
synced 2026-03-31 04:23:40 +00:00
feat: move all frontend projects under the same Angular workspace (#1141)
* feat: move all frontend projects under the same Angular workspace * Refactor/angular workspace (#1154) * update frontend build steps Co-authored-by: waterplea <alexander@inkin.ru> Co-authored-by: Matt Hill <matthewonthemoon@gmail.com> Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
This commit is contained in:
252
frontend/projects/ui/src/app/util/countries.json
Normal file
252
frontend/projects/ui/src/app/util/countries.json
Normal file
@@ -0,0 +1,252 @@
|
||||
{
|
||||
"AD": "Andorra",
|
||||
"AE": "United Arab Emirates",
|
||||
"AF": "Afghanistan",
|
||||
"AG": "Antigua and Barbuda",
|
||||
"AI": "Anguilla",
|
||||
"AL": "Albania",
|
||||
"AM": "Armenia",
|
||||
"AO": "Angola",
|
||||
"AQ": "Antarctica",
|
||||
"AR": "Argentina",
|
||||
"AS": "American Samoa",
|
||||
"AT": "Austria",
|
||||
"AU": "Australia",
|
||||
"AW": "Aruba",
|
||||
"AX": "Aland Islands",
|
||||
"AZ": "Azerbaijan",
|
||||
"BA": "Bosnia and Herzegovina",
|
||||
"BB": "Barbados",
|
||||
"BD": "Bangladesh",
|
||||
"BE": "Belgium",
|
||||
"BF": "Burkina Faso",
|
||||
"BG": "Bulgaria",
|
||||
"BH": "Bahrain",
|
||||
"BI": "Burundi",
|
||||
"BJ": "Benin",
|
||||
"BL": "Saint Barthelemy",
|
||||
"BM": "Bermuda",
|
||||
"BN": "Brunei",
|
||||
"BO": "Bolivia",
|
||||
"BQ": "Bonaire, Saint Eustatius and Saba ",
|
||||
"BR": "Brazil",
|
||||
"BS": "Bahamas",
|
||||
"BT": "Bhutan",
|
||||
"BV": "Bouvet Island",
|
||||
"BW": "Botswana",
|
||||
"BY": "Belarus",
|
||||
"BZ": "Belize",
|
||||
"CA": "Canada",
|
||||
"CC": "Cocos Islands",
|
||||
"CD": "Democratic Republic of the Congo",
|
||||
"CF": "Central African Republic",
|
||||
"CG": "Republic of the Congo",
|
||||
"CH": "Switzerland",
|
||||
"CI": "Ivory Coast",
|
||||
"CK": "Cook Islands",
|
||||
"CL": "Chile",
|
||||
"CM": "Cameroon",
|
||||
"CN": "China",
|
||||
"CO": "Colombia",
|
||||
"CR": "Costa Rica",
|
||||
"CU": "Cuba",
|
||||
"CV": "Cape Verde",
|
||||
"CW": "Curacao",
|
||||
"CX": "Christmas Island",
|
||||
"CY": "Cyprus",
|
||||
"CZ": "Czech Republic",
|
||||
"DE": "Germany",
|
||||
"DJ": "Djibouti",
|
||||
"DK": "Denmark",
|
||||
"DM": "Dominica",
|
||||
"DO": "Dominican Republic",
|
||||
"DZ": "Algeria",
|
||||
"EC": "Ecuador",
|
||||
"EE": "Estonia",
|
||||
"EG": "Egypt",
|
||||
"EH": "Western Sahara",
|
||||
"ER": "Eritrea",
|
||||
"ES": "Spain",
|
||||
"ET": "Ethiopia",
|
||||
"FI": "Finland",
|
||||
"FJ": "Fiji",
|
||||
"FK": "Falkland Islands",
|
||||
"FM": "Micronesia",
|
||||
"FO": "Faroe Islands",
|
||||
"FR": "France",
|
||||
"GA": "Gabon",
|
||||
"GB": "United Kingdom",
|
||||
"GD": "Grenada",
|
||||
"GE": "Georgia",
|
||||
"GF": "French Guiana",
|
||||
"GG": "Guernsey",
|
||||
"GH": "Ghana",
|
||||
"GI": "Gibraltar",
|
||||
"GL": "Greenland",
|
||||
"GM": "Gambia",
|
||||
"GN": "Guinea",
|
||||
"GP": "Guadeloupe",
|
||||
"GQ": "Equatorial Guinea",
|
||||
"GR": "Greece",
|
||||
"GS": "South Georgia and the South Sandwich Islands",
|
||||
"GT": "Guatemala",
|
||||
"GU": "Guam",
|
||||
"GW": "Guinea-Bissau",
|
||||
"GY": "Guyana",
|
||||
"HK": "Hong Kong",
|
||||
"HM": "Heard Island and McDonald Islands",
|
||||
"HN": "Honduras",
|
||||
"HR": "Croatia",
|
||||
"HT": "Haiti",
|
||||
"HU": "Hungary",
|
||||
"ID": "Indonesia",
|
||||
"IE": "Ireland",
|
||||
"IL": "Israel",
|
||||
"IM": "Isle of Man",
|
||||
"IN": "India",
|
||||
"IO": "British Indian Ocean Territory",
|
||||
"IQ": "Iraq",
|
||||
"IR": "Iran",
|
||||
"IS": "Iceland",
|
||||
"IT": "Italy",
|
||||
"JE": "Jersey",
|
||||
"JM": "Jamaica",
|
||||
"JO": "Jordan",
|
||||
"JP": "Japan",
|
||||
"KE": "Kenya",
|
||||
"KG": "Kyrgyzstan",
|
||||
"KH": "Cambodia",
|
||||
"KI": "Kiribati",
|
||||
"KM": "Comoros",
|
||||
"KN": "Saint Kitts and Nevis",
|
||||
"KP": "North Korea",
|
||||
"KR": "South Korea",
|
||||
"KW": "Kuwait",
|
||||
"KY": "Cayman Islands",
|
||||
"KZ": "Kazakhstan",
|
||||
"LA": "Laos",
|
||||
"LB": "Lebanon",
|
||||
"LC": "Saint Lucia",
|
||||
"LI": "Liechtenstein",
|
||||
"LK": "Sri Lanka",
|
||||
"LR": "Liberia",
|
||||
"LS": "Lesotho",
|
||||
"LT": "Lithuania",
|
||||
"LU": "Luxembourg",
|
||||
"LV": "Latvia",
|
||||
"LY": "Libya",
|
||||
"MA": "Morocco",
|
||||
"MC": "Monaco",
|
||||
"MD": "Moldova",
|
||||
"ME": "Montenegro",
|
||||
"MF": "Saint Martin",
|
||||
"MG": "Madagascar",
|
||||
"MH": "Marshall Islands",
|
||||
"MK": "Macedonia",
|
||||
"ML": "Mali",
|
||||
"MM": "Myanmar",
|
||||
"MN": "Mongolia",
|
||||
"MO": "Macao",
|
||||
"MP": "Northern Mariana Islands",
|
||||
"MQ": "Martinique",
|
||||
"MR": "Mauritania",
|
||||
"MS": "Montserrat",
|
||||
"MT": "Malta",
|
||||
"MU": "Mauritius",
|
||||
"MV": "Maldives",
|
||||
"MW": "Malawi",
|
||||
"MX": "Mexico",
|
||||
"MY": "Malaysia",
|
||||
"MZ": "Mozambique",
|
||||
"NA": "Namibia",
|
||||
"NC": "New Caledonia",
|
||||
"NE": "Niger",
|
||||
"NF": "Norfolk Island",
|
||||
"NG": "Nigeria",
|
||||
"NI": "Nicaragua",
|
||||
"NL": "Netherlands",
|
||||
"NO": "Norway",
|
||||
"NP": "Nepal",
|
||||
"NR": "Nauru",
|
||||
"NU": "Niue",
|
||||
"NZ": "New Zealand",
|
||||
"OM": "Oman",
|
||||
"PA": "Panama",
|
||||
"PE": "Peru",
|
||||
"PF": "French Polynesia",
|
||||
"PG": "Papua New Guinea",
|
||||
"PH": "Philippines",
|
||||
"PK": "Pakistan",
|
||||
"PL": "Poland",
|
||||
"PM": "Saint Pierre and Miquelon",
|
||||
"PN": "Pitcairn",
|
||||
"PR": "Puerto Rico",
|
||||
"PS": "Palestinian Territory",
|
||||
"PT": "Portugal",
|
||||
"PW": "Palau",
|
||||
"PY": "Paraguay",
|
||||
"QA": "Qatar",
|
||||
"RE": "Reunion",
|
||||
"RO": "Romania",
|
||||
"RS": "Serbia",
|
||||
"RU": "Russia",
|
||||
"RW": "Rwanda",
|
||||
"SA": "Saudi Arabia",
|
||||
"SB": "Solomon Islands",
|
||||
"SC": "Seychelles",
|
||||
"SD": "Sudan",
|
||||
"SE": "Sweden",
|
||||
"SG": "Singapore",
|
||||
"SH": "Saint Helena",
|
||||
"SI": "Slovenia",
|
||||
"SJ": "Svalbard and Jan Mayen",
|
||||
"SK": "Slovakia",
|
||||
"SL": "Sierra Leone",
|
||||
"SM": "San Marino",
|
||||
"SN": "Senegal",
|
||||
"SO": "Somalia",
|
||||
"SR": "Suriname",
|
||||
"SS": "South Sudan",
|
||||
"ST": "Sao Tome and Principe",
|
||||
"SV": "El Salvador",
|
||||
"SX": "Sint Maarten",
|
||||
"SY": "Syria",
|
||||
"SZ": "Swaziland",
|
||||
"TC": "Turks and Caicos Islands",
|
||||
"TD": "Chad",
|
||||
"TF": "French Southern Territories",
|
||||
"TG": "Togo",
|
||||
"TH": "Thailand",
|
||||
"TJ": "Tajikistan",
|
||||
"TK": "Tokelau",
|
||||
"TL": "East Timor",
|
||||
"TM": "Turkmenistan",
|
||||
"TN": "Tunisia",
|
||||
"TO": "Tonga",
|
||||
"TR": "Turkey",
|
||||
"TT": "Trinidad and Tobago",
|
||||
"TV": "Tuvalu",
|
||||
"TW": "Taiwan",
|
||||
"TZ": "Tanzania",
|
||||
"UA": "Ukraine",
|
||||
"UG": "Uganda",
|
||||
"UM": "United States Minor Outlying Islands",
|
||||
"US": "United States",
|
||||
"UY": "Uruguay",
|
||||
"UZ": "Uzbekistan",
|
||||
"VA": "Vatican",
|
||||
"VC": "Saint Vincent and the Grenadines",
|
||||
"VE": "Venezuela",
|
||||
"VG": "British Virgin Islands",
|
||||
"VI": "U.S. Virgin Islands",
|
||||
"VN": "Vietnam",
|
||||
"VU": "Vanuatu",
|
||||
"WF": "Wallis and Futuna",
|
||||
"WS": "Samoa",
|
||||
"XK": "Kosovo",
|
||||
"YE": "Yemen",
|
||||
"YT": "Mayotte",
|
||||
"ZA": "South Africa",
|
||||
"ZM": "Zambia",
|
||||
"ZW": "Zimbabwe"
|
||||
}
|
||||
35
frontend/projects/ui/src/app/util/get-package-info.ts
Normal file
35
frontend/projects/ui/src/app/util/get-package-info.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { PackageDataEntry } from '../services/patch-db/data-model'
|
||||
import {
|
||||
DependencyStatus,
|
||||
HealthStatus,
|
||||
PrimaryRendering,
|
||||
renderPkgStatus,
|
||||
StatusRendering,
|
||||
} from '../services/pkg-status-rendering.service'
|
||||
import { isEmptyObject } from './misc.util'
|
||||
import {
|
||||
packageLoadingProgress,
|
||||
ProgressData,
|
||||
} from './package-loading-progress'
|
||||
import { Subscription } from 'rxjs'
|
||||
|
||||
export function getPackageInfo(entry: PackageDataEntry): PkgInfo {
|
||||
const statuses = renderPkgStatus(entry)
|
||||
|
||||
return {
|
||||
entry,
|
||||
primaryRendering: PrimaryRendering[statuses.primary],
|
||||
installProgress: packageLoadingProgress(entry['install-progress']),
|
||||
error:
|
||||
statuses.health === HealthStatus.Failure ||
|
||||
statuses.dependency === DependencyStatus.Warning,
|
||||
}
|
||||
}
|
||||
|
||||
export interface PkgInfo {
|
||||
entry: PackageDataEntry
|
||||
primaryRendering: StatusRendering
|
||||
installProgress: ProgressData | null
|
||||
error: boolean
|
||||
sub?: Subscription | null
|
||||
}
|
||||
197
frontend/projects/ui/src/app/util/misc.util.ts
Normal file
197
frontend/projects/ui/src/app/util/misc.util.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import { OperatorFunction } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
export type Omit<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>
|
||||
export type PromiseRes<T> = { result: 'resolve', value: T } | { result: 'reject', value: Error }
|
||||
|
||||
export interface MappedBackupTarget<T> {
|
||||
id: string
|
||||
hasValidBackup: boolean
|
||||
entry: T
|
||||
}
|
||||
|
||||
export interface DependentInfo {
|
||||
id: string
|
||||
title: string
|
||||
version?: string
|
||||
}
|
||||
|
||||
export function trace<T> (t: T): T {
|
||||
console.log(`TRACE`, t)
|
||||
return t
|
||||
}
|
||||
|
||||
// curried description. This allows e.g somePromise.thentraceDesc('my result'))
|
||||
export function traceDesc<T> (description: string): (t: T) => T {
|
||||
return t => {
|
||||
console.log(`TRACE`, description, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
// for use in observables. This allows e.g. someObservable.pipe(traceM('my result'))
|
||||
// the practical equivalent of `tap(t => console.log(t, description))`
|
||||
export function traceWheel<T> (description?: string): OperatorFunction<T, T> {
|
||||
return description ? map(traceDesc(description)) : map(trace)
|
||||
}
|
||||
|
||||
export function traceThrowDesc<T> (description: string, t: T | undefined): T {
|
||||
if (!t) throw new Error(description)
|
||||
return t
|
||||
}
|
||||
|
||||
export function thenReturn<T> (act1 : () => Promise<any>, t: T): Promise<T> {
|
||||
return act1().then(() => t)
|
||||
}
|
||||
|
||||
export function modulateTime (ts: Date, count: number, unit: 'days' | 'hours' | 'minutes' | 'seconds' ) {
|
||||
const ms = inMs(count, unit)
|
||||
const toReturn = new Date(ts)
|
||||
toReturn.setMilliseconds( toReturn.getMilliseconds() + ms)
|
||||
return toReturn
|
||||
}
|
||||
|
||||
export function inMs ( count: number, unit: 'days' | 'hours' | 'minutes' | 'seconds' ) {
|
||||
switch (unit){
|
||||
case 'seconds' : return count * 1000
|
||||
case 'minutes' : return inMs(count * 60, 'seconds')
|
||||
case 'hours' : return inMs(count * 60, 'minutes')
|
||||
case 'days' : return inMs(count * 24, 'hours')
|
||||
}
|
||||
}
|
||||
|
||||
export async function tryAll<T1, T2> ( promises: [Promise<T1>, Promise<T2>]): Promise<[PromiseRes<T1>, PromiseRes<T2>]>
|
||||
export async function tryAll ( promises: Promise<any>[] ): Promise<PromiseRes<any>[]> {
|
||||
return Promise.all(promises.map(
|
||||
p => p
|
||||
.then (r => ({ result: 'resolve' as 'resolve', value: r }))
|
||||
.catch(e => ({ result: 'reject' as 'reject', value: e })),
|
||||
))
|
||||
}
|
||||
|
||||
// arr1 - arr2
|
||||
export function diff<T> (arr1: T[], arr2: T[]): T[] {
|
||||
return arr1.filter(x => !arr2.includes(x))
|
||||
}
|
||||
|
||||
// arr1 & arr2
|
||||
export function both<T> (arr1: T[], arr2: T[]): T[] {
|
||||
return arr1.filter(x => arr2.includes(x))
|
||||
}
|
||||
|
||||
export async function doForAtLeast (promises: Promise<any>[], minTime: number): Promise<any[]> {
|
||||
const returned = await Promise.all(promises.concat(pauseFor(minTime)))
|
||||
returned.pop()
|
||||
return returned
|
||||
}
|
||||
|
||||
export function isObject (val: any): boolean {
|
||||
return val && typeof val === 'object' && !Array.isArray(val)
|
||||
}
|
||||
|
||||
export function isEmptyObject (obj: object): boolean {
|
||||
if (obj === undefined) return true
|
||||
return !Object.keys(obj).length
|
||||
}
|
||||
|
||||
export function pauseFor (ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
export type Valued<T> = { [s: string]: T }
|
||||
|
||||
export function toObject<T> (t: T[], map: (t0: T) => string): Valued<T> {
|
||||
return t.reduce( (acc, next) => {
|
||||
acc[map(next)] = next
|
||||
return acc
|
||||
}, { } as Valued<T>)
|
||||
}
|
||||
|
||||
export function toDedupObject<T> (t: T[], t2: T[], map: (t0: T) => string): Valued<T> {
|
||||
return toObject(t.concat(t2), map)
|
||||
}
|
||||
|
||||
export function update<T> (t: Valued<T>, u: Valued<T>): Valued<T> {
|
||||
return { ...t, ...u}
|
||||
}
|
||||
|
||||
export function fromObject<T> (o : Valued<T>): T[] {
|
||||
return Object.values(o)
|
||||
}
|
||||
|
||||
export function deepCloneUnknown<T> (value: T): T {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return deepCloneArray(value)
|
||||
}
|
||||
return deepCloneObject(value)
|
||||
}
|
||||
|
||||
export function deepCloneObject<T> (source: T) {
|
||||
const result = { }
|
||||
Object.keys(source).forEach(key => {
|
||||
const value = source[key]
|
||||
result[key] = deepCloneUnknown(value)
|
||||
}, { })
|
||||
return result as T
|
||||
}
|
||||
|
||||
export function deepCloneArray (collection: any) {
|
||||
return collection.map(value => {
|
||||
return deepCloneUnknown(value)
|
||||
})
|
||||
}
|
||||
|
||||
export function partitionArray<T> (ts: T[], condition: (t: T) => boolean): [T[], T[]] {
|
||||
const yes = [] as T[]
|
||||
const no = [] as T[]
|
||||
ts.forEach(t => {
|
||||
if (condition(t)) {
|
||||
yes.push(t)
|
||||
} else {
|
||||
no.push(t)
|
||||
}
|
||||
})
|
||||
return [yes, no]
|
||||
}
|
||||
|
||||
export function uniqueBy<T> (ts: T[], uniqueBy: (t: T) => string, prioritize: (t1: T, t2: T) => T) {
|
||||
return Object.values(ts.reduce((acc, next) => {
|
||||
const previousValue = acc[uniqueBy(next)]
|
||||
if (previousValue) {
|
||||
acc[uniqueBy(next)] = prioritize(acc[uniqueBy(next)], previousValue)
|
||||
} else {
|
||||
acc[uniqueBy(next)] = previousValue
|
||||
}
|
||||
return acc
|
||||
}, { }))
|
||||
}
|
||||
|
||||
export function capitalizeFirstLetter (string: string): string {
|
||||
return string.charAt(0).toUpperCase() + string.slice(1)
|
||||
}
|
||||
|
||||
export const exists = (t: any) => {
|
||||
return t !== undefined
|
||||
}
|
||||
|
||||
export type DeepPartial<T> = {
|
||||
[k in keyof T]?: DeepPartial<T[k]>
|
||||
}
|
||||
|
||||
export function debounce (delay: number = 300): MethodDecorator {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const timeoutKey = Symbol()
|
||||
|
||||
const original = descriptor.value
|
||||
|
||||
descriptor.value = function (...args) {
|
||||
clearTimeout(this[timeoutKey])
|
||||
this[timeoutKey] = setTimeout(() => original.apply(this, args), delay)
|
||||
}
|
||||
|
||||
return descriptor
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { InstallProgress } from 'src/app/services/patch-db/data-model'
|
||||
import { isEmptyObject } from './misc.util'
|
||||
|
||||
export function packageLoadingProgress(
|
||||
loadData: InstallProgress,
|
||||
): ProgressData | null {
|
||||
if (isEmptyObject(loadData)) {
|
||||
return null
|
||||
}
|
||||
|
||||
let {
|
||||
downloaded,
|
||||
validated,
|
||||
unpacked,
|
||||
size,
|
||||
'download-complete': downloadComplete,
|
||||
'validation-complete': validationComplete,
|
||||
'unpack-complete': unpackComplete,
|
||||
} = loadData
|
||||
|
||||
// only permit 100% when "complete" == true
|
||||
downloaded = downloadComplete ? size : Math.max(downloaded - 1, 0)
|
||||
validated = validationComplete ? size : Math.max(validated - 1, 0)
|
||||
unpacked = unpackComplete ? size : Math.max(unpacked - 1, 0)
|
||||
|
||||
const downloadWeight = 1
|
||||
const validateWeight = 0.2
|
||||
const unpackWeight = 0.7
|
||||
|
||||
const numerator = Math.floor(
|
||||
downloadWeight * downloaded +
|
||||
validateWeight * validated +
|
||||
unpackWeight * unpacked,
|
||||
)
|
||||
|
||||
const denominator = Math.floor(
|
||||
size * (downloadWeight + validateWeight + unpackWeight),
|
||||
)
|
||||
const totalProgress = Math.floor((100 * numerator) / denominator)
|
||||
|
||||
return {
|
||||
totalProgress,
|
||||
downloadProgress: Math.floor((100 * downloaded) / size),
|
||||
validateProgress: Math.floor((100 * validated) / size),
|
||||
unpackProgress: Math.floor((100 * unpacked) / size),
|
||||
isComplete: downloadComplete && validationComplete && unpackComplete,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProgressData {
|
||||
totalProgress: number
|
||||
downloadProgress: number
|
||||
validateProgress: number
|
||||
unpackProgress: number
|
||||
isComplete: boolean
|
||||
}
|
||||
50
frontend/projects/ui/src/app/util/parse-data-model.ts
Normal file
50
frontend/projects/ui/src/app/util/parse-data-model.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
DataModel,
|
||||
PackageDataEntry,
|
||||
RecoveredPackageDataEntry,
|
||||
} from '../services/patch-db/data-model'
|
||||
|
||||
export function parseDataModel (data: DataModel): ParsedData {
|
||||
const all = JSON.parse(JSON.stringify(data['package-data'])) as {
|
||||
[id: string]: PackageDataEntry;
|
||||
}
|
||||
|
||||
const order = [...(data.ui['pkg-order'] || [])]
|
||||
const pkgs = []
|
||||
const recoveredPkgs = Object.entries(data['recovered-packages'])
|
||||
.filter(([id, _]) => !all[id])
|
||||
.map(([id, val]) => ({
|
||||
...val,
|
||||
id,
|
||||
}))
|
||||
|
||||
// add known packages in preferential order
|
||||
order.forEach((id) => {
|
||||
if (all[id]) {
|
||||
pkgs.push(all[id])
|
||||
|
||||
delete all[id]
|
||||
}
|
||||
})
|
||||
|
||||
// unshift unknown packages
|
||||
Object.values(all).forEach((pkg) => {
|
||||
pkgs.unshift(pkg)
|
||||
})
|
||||
|
||||
return {
|
||||
order,
|
||||
pkgs,
|
||||
recoveredPkgs,
|
||||
}
|
||||
}
|
||||
|
||||
export interface RecoveredInfo extends RecoveredPackageDataEntry {
|
||||
id: string
|
||||
}
|
||||
|
||||
interface ParsedData {
|
||||
order: string[]
|
||||
pkgs: PackageDataEntry[]
|
||||
recoveredPkgs: RecoveredInfo[]
|
||||
}
|
||||
215
frontend/projects/ui/src/app/util/properties.util.ts
Normal file
215
frontend/projects/ui/src/app/util/properties.util.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import * as Ajv from 'ajv'
|
||||
import { applyOperation } from 'fast-json-patch'
|
||||
|
||||
|
||||
export type ValidVersion = 1 | 2
|
||||
|
||||
function has<Obj extends {}, K extends string>(obj: Obj, key: K): obj is (Obj & { [P in K]: unknown }) {
|
||||
return key in obj
|
||||
}
|
||||
|
||||
|
||||
const ajv = new Ajv({ jsonPointers: true, allErrors: true, nullable: true })
|
||||
const ajvWithDefaults = new Ajv({ jsonPointers: true, allErrors: true, useDefaults: true, nullable: true, removeAdditional: 'failing' })
|
||||
|
||||
const schemaV1 = {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': { 'type': 'string' },
|
||||
'value': { 'type': 'string' },
|
||||
'description': { 'type': 'string', 'nullable': true, 'default': null },
|
||||
'copyable': { 'type': 'boolean', 'default': false },
|
||||
'qr': { 'type': 'boolean', 'default': false },
|
||||
},
|
||||
'required': ['name', 'value', 'copyable', 'qr'],
|
||||
'additionalProperties': false,
|
||||
}
|
||||
const schemaV1Compiled = ajv.compile(schemaV1)
|
||||
function isSchemaV1(properties: unknown): properties is PropertiesV1 {
|
||||
return schemaV1Compiled(properties) as any
|
||||
}
|
||||
const schemaV1CompiledWithDefaults = ajvWithDefaults.compile(schemaV1)
|
||||
const schemaV2 = {
|
||||
'anyOf': [
|
||||
{
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'type': { 'type': 'string', 'const': 'string' },
|
||||
'value': { 'type': 'string' },
|
||||
'description': { 'type': 'string', 'nullable': true, 'default': null },
|
||||
'copyable': { 'type': 'boolean', 'default': false },
|
||||
'qr': { 'type': 'boolean', 'default': false },
|
||||
'masked': { 'type': 'boolean', 'default': false },
|
||||
},
|
||||
'required': ['type', 'value', 'description', 'copyable', 'qr', 'masked'],
|
||||
'additionalProperties': false,
|
||||
},
|
||||
{
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'type': { 'type': 'string', 'const': 'object' },
|
||||
'value': {
|
||||
'type': 'object',
|
||||
'patternProperties': {
|
||||
'^.*$': {
|
||||
'$ref': '#',
|
||||
},
|
||||
},
|
||||
},
|
||||
'description': { 'type': 'string', 'nullable': true, 'default': null },
|
||||
|
||||
},
|
||||
'required': ['type', 'value', 'description'],
|
||||
'additionalProperties': false,
|
||||
},
|
||||
],
|
||||
}
|
||||
const schemaV2Compiled = ajv.compile(schemaV2)
|
||||
const schemaV2CompiledWithDefaults = ajvWithDefaults.compile(schemaV2)
|
||||
|
||||
export function parsePropertiesPermissive (properties: unknown, errorCallback: (err: Error) => any = console.warn): PackageProperties {
|
||||
if (typeof properties !== 'object' || properties === null) {
|
||||
errorCallback(new TypeError(`${properties} is not an object`))
|
||||
return {}
|
||||
}
|
||||
// @TODO still need this conditional?
|
||||
if (!has(properties, 'version') || !has(properties, 'data') || typeof properties.version !== 'number' || !properties.data) {
|
||||
return Object.entries(properties)
|
||||
.filter(([_, value]) => {
|
||||
if (typeof value === 'string') {
|
||||
return true
|
||||
} else {
|
||||
errorCallback(new TypeError(`${value} is not a string`))
|
||||
return false
|
||||
}
|
||||
})
|
||||
.map(([name, value]) => ({
|
||||
name,
|
||||
value: {
|
||||
value: String(value),
|
||||
description: null,
|
||||
copyable: false,
|
||||
qr: false,
|
||||
masked: false,
|
||||
},
|
||||
}))
|
||||
.reduce((acc, { name, value }) => {
|
||||
acc[name] = value
|
||||
return acc
|
||||
}, { })
|
||||
|
||||
}
|
||||
switch (properties.version) {
|
||||
case 1:
|
||||
return parsePropertiesV1Permissive(properties.data, errorCallback)
|
||||
case 2:
|
||||
return parsePropertiesV2Permissive(properties.data, errorCallback)
|
||||
default:
|
||||
errorCallback(new Error(`unknown properties version ${properties.version}, attempting to parse as v2`))
|
||||
return parsePropertiesV2Permissive(properties.data, errorCallback)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
function parsePropertiesV1Permissive (properties: unknown, errorCallback: (err: Error) => any): PackageProperties {
|
||||
if (!Array.isArray(properties)) {
|
||||
errorCallback(new TypeError(`${properties} is not an array`))
|
||||
return {}
|
||||
}
|
||||
return properties.reduce((prev: PackagePropertiesV2, cur: unknown, idx: number) => {
|
||||
if(isSchemaV1(cur)) {
|
||||
prev[cur.name] = {
|
||||
type: 'string',
|
||||
value: cur.value,
|
||||
description: cur.description,
|
||||
copyable: cur.copyable,
|
||||
qr: cur.qr,
|
||||
masked: false,
|
||||
}
|
||||
}
|
||||
else if (schemaV1Compiled.errors) {
|
||||
for (let err of schemaV1Compiled.errors) {
|
||||
errorCallback(new Error(`/data/${idx}${err.dataPath}: ${err.message}`))
|
||||
if (err.dataPath) {
|
||||
applyOperation(cur, { op: 'replace', path: err.dataPath, value: undefined })
|
||||
}
|
||||
}
|
||||
if (!schemaV1CompiledWithDefaults(cur)) {
|
||||
for (let err of schemaV1CompiledWithDefaults.errors) {
|
||||
errorCallback(new Error(`/data/${idx}${err.dataPath}: ${err.message}`))
|
||||
}
|
||||
return prev
|
||||
}
|
||||
}
|
||||
return prev
|
||||
}, { })
|
||||
}
|
||||
function parsePropertiesV2Permissive (properties: unknown, errorCallback: (err: Error) => any): PackageProperties {
|
||||
if (typeof properties !== 'object' || properties === null) {
|
||||
errorCallback(new TypeError(`${properties} is not an object`))
|
||||
return {}
|
||||
}
|
||||
return Object.entries(properties).reduce((prev, [name, value], idx) => {
|
||||
schemaV2Compiled(value)
|
||||
if (schemaV2Compiled.errors) {
|
||||
for (let err of schemaV2Compiled.errors) {
|
||||
errorCallback(new Error(`/data/${idx}${err.dataPath}: ${err.message}`))
|
||||
if (err.dataPath) {
|
||||
applyOperation(value, { op: 'replace', path: err.dataPath, value: undefined })
|
||||
}
|
||||
}
|
||||
if (!schemaV2CompiledWithDefaults(value)) {
|
||||
for (let err of schemaV2CompiledWithDefaults.errors) {
|
||||
errorCallback(new Error(`/data/${idx}${err.dataPath}: ${err.message}`))
|
||||
}
|
||||
return prev
|
||||
}
|
||||
}
|
||||
prev[name] = value
|
||||
return prev
|
||||
}, { })
|
||||
}
|
||||
interface PropertiesV1 {
|
||||
name: string
|
||||
value: string
|
||||
description: string | null
|
||||
copyable: boolean
|
||||
qr: boolean
|
||||
}
|
||||
|
||||
type PackagePropertiesV1 = PropertiesV1[]
|
||||
export type PackageProperties = PackagePropertiesV2
|
||||
|
||||
export type PackagePropertiesVersioned<T extends number> = {
|
||||
version: T,
|
||||
data: PackagePropertiesVersionedData<T>
|
||||
}
|
||||
|
||||
export type PackagePropertiesVersionedData<T extends number> =
|
||||
T extends 1 ? PackagePropertiesV1 :
|
||||
T extends 2 ? PackagePropertiesV2 :
|
||||
never
|
||||
|
||||
|
||||
interface PackagePropertiesV2 {
|
||||
[name: string]: PackagePropertyString | PackagePropertyObject
|
||||
}
|
||||
|
||||
interface PackagePropertyBase {
|
||||
type: 'string' | 'object'
|
||||
description: string | null
|
||||
}
|
||||
|
||||
interface PackagePropertyString extends PackagePropertyBase {
|
||||
type: 'string'
|
||||
value: string
|
||||
copyable: boolean
|
||||
qr: boolean
|
||||
masked: boolean
|
||||
}
|
||||
|
||||
interface PackagePropertyObject extends PackagePropertyBase {
|
||||
type: 'object'
|
||||
value: PackagePropertiesV2
|
||||
}
|
||||
94
frontend/projects/ui/src/app/util/rxjs.util.ts
Normal file
94
frontend/projects/ui/src/app/util/rxjs.util.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Observable, from, interval, race, OperatorFunction, Observer, combineLatest } from 'rxjs'
|
||||
import { take, map, concatMap } from 'rxjs/operators'
|
||||
|
||||
export function fromAsync$<S, T> (async: (s: S) => Promise<T>, s: S): Observable<T>
|
||||
export function fromAsync$<T> (async: () => Promise<T>): Observable<T>
|
||||
export function fromAsync$<S, T> (async: (s: S) => Promise<T>, s?: S): Observable<T> {
|
||||
return from(async(s as S))
|
||||
}
|
||||
|
||||
export function fromAsyncP<T> (async: () => Promise<T>): Promise<T>
|
||||
export function fromAsyncP<S, T> (async: (s: S) => Promise<T>, s?: S): Promise<T> {
|
||||
return async(s as S)
|
||||
}
|
||||
|
||||
// emits + completes after ms
|
||||
export function emitAfter$ (ms: number): Observable<number> {
|
||||
return interval(ms).pipe(take(1))
|
||||
}
|
||||
|
||||
// throws unless source observable emits withing timeout
|
||||
export function throwIn<T> (timeout: number): OperatorFunction<T, T> {
|
||||
return o => race(
|
||||
o,
|
||||
emitAfter$(timeout).pipe(map(() => { throw new Error('timeout') } )))
|
||||
}
|
||||
|
||||
// o.pipe(squash) : Observable<void> regardless of o emission type.
|
||||
export const squash = map(() => { })
|
||||
|
||||
/*
|
||||
The main purpose of fromSync$ is to normalize error handling during a sequence
|
||||
of actions beginning with a standard synchronous action and followed by a pipe.
|
||||
For example, imagine we have `f(s: S): T` which might throw, and we wish to define the following:
|
||||
```
|
||||
function observableF(t: T): Observable<any> {
|
||||
const s = f(t)
|
||||
return someFunctionReturningAnObservable(s)
|
||||
}
|
||||
```
|
||||
|
||||
For the caller, `observableF(t).pipe(...).subscribe({ error: e => console.error('observable errored!') })`
|
||||
might throw an error from `f` which does not result in 'observable errored!' being logged.
|
||||
We could fix this with...
|
||||
```
|
||||
function observableF(t: T): Observable<any> {
|
||||
try {
|
||||
const s = f(t)
|
||||
return someFunctionReturningAnObservable(s)
|
||||
} catch(e) {
|
||||
return throwError(e)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
or we could use fromSync as below
|
||||
```
|
||||
function observableF(t: T): Observable<any> {
|
||||
return fromSync$(f, t).concatMap(someFunctionReturningAnObservable)
|
||||
}
|
||||
```
|
||||
*/
|
||||
export function fromSync$<S, T> (sync: (s: S) => T, s: S): Observable<T>
|
||||
export function fromSync$<T> (sync: () => T): Observable<T>
|
||||
export function fromSync$<S, T> (sync: (s: S) => T, s?: S): Observable<T> {
|
||||
return new Observable( (subscriber: Observer<T>) => {
|
||||
try {
|
||||
subscriber.next(sync(s as S))
|
||||
subscriber.complete()
|
||||
} catch (e) {
|
||||
subscriber.error(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
this function concats the current values (e.g in behavior subjects) or next values (in traditional observables) to a collection of values in a pipe.
|
||||
e.g. if t: Observable<T>, and o1: Observable<O1> o2: Observable<O2> then t.pipe(concatObservableValues([o1, o2])): Observable<[T1, O1, O2]> and emits iff t emits.
|
||||
Note that the standard combineLatest([t, o1, o2]) is also of type Observable<[T, O2, O2]>, but this observable triggers when any of t, o1, o2 emits.
|
||||
*/
|
||||
export function concatObservableValues<T, O> (observables: [Observable<O>]): OperatorFunction<T, [T, O]>
|
||||
export function concatObservableValues<T, O> (observables: [Observable<O>]): OperatorFunction<[T], [T, O]>
|
||||
export function concatObservableValues<T1, T2, O> (observables: [Observable<O>]): OperatorFunction<[T1, T2], [T1, T2, O]>
|
||||
export function concatObservableValues<T, O1, O2> (observables: [Observable<O1>, Observable<O2>]): OperatorFunction<[T], [T, O1, O2]>
|
||||
export function concatObservableValues<T1, T2, O1, O2> (observables: [Observable<O1>, Observable<O2>]): OperatorFunction<[T1, T2], [T1, T2, O1, O2]>
|
||||
export function concatObservableValues (observables: Observable<any>[]): OperatorFunction<any[], any[]> {
|
||||
return o => o.pipe(concatMap(args => combineLatest(observables).pipe(
|
||||
map(obs => {
|
||||
if (!(args instanceof Array)) return [args, ...obs]
|
||||
return [...args, ...obs]
|
||||
}),
|
||||
take(1),
|
||||
),
|
||||
))
|
||||
}
|
||||
22
frontend/projects/ui/src/app/util/web.util.ts
Normal file
22
frontend/projects/ui/src/app/util/web.util.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
export async function copyToClipboard (str: string): Promise<boolean> {
|
||||
if (window.isSecureContext) {
|
||||
return navigator.clipboard.writeText(str)
|
||||
.then(() => {
|
||||
return true
|
||||
})
|
||||
.catch(err => {
|
||||
return false
|
||||
})
|
||||
} else {
|
||||
const el = document.createElement('textarea')
|
||||
el.value = str
|
||||
el.setAttribute('readonly', '')
|
||||
el.style.position = 'absolute'
|
||||
el.style.left = '-9999px'
|
||||
document.body.appendChild(el)
|
||||
el.select()
|
||||
const copy = document.execCommand('copy')
|
||||
document.body.removeChild(el)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user