@controlplane/cli
Version:
Control Plane Corporation CLI
115 lines • 2.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBase64 = exports.isNameValid = exports.k8sKeySort = exports.toSortedYamlString = exports.toSortedJson = void 0;
const js_yaml_1 = require("js-yaml");
var stringify = require('json-stable-stringify');
const validName = /^[a-z]([-a-z0-9])*[a-z0-9]$/;
function toSortedJsonString(obj) {
return stringify(obj, {
cmp: (a, b) => k8sKeySort(a.key, b.key),
});
}
function toSortedJson(obj) {
return JSON.parse(toSortedJsonString(obj));
}
exports.toSortedJson = toSortedJson;
function toSortedYamlString(obj) {
return (0, js_yaml_1.safeDump)(obj, {
indent: 2,
noRefs: true,
skipInvalid: true,
sortKeys: k8sKeySort,
});
}
exports.toSortedYamlString = toSortedYamlString;
const firstKeys = [
//
'kind',
'itemKind',
'name',
'description',
'alias',
'tags',
'origin',
'type',
'provider',
'data',
];
const lastKeys = [
//
'version',
'id',
'spec',
'status',
'created',
'lastModified',
'manifest',
'links',
];
function k8sKeySort(a, b) {
if (a == b) {
return 0;
}
const fa = firstKeys.indexOf(a);
const fb = firstKeys.indexOf(b);
// 2: both at the top
if (fa >= 0 && fb >= 0) {
return fa - fb;
}
const la = lastKeys.indexOf(a);
const lb = lastKeys.indexOf(b);
// 1: both at the bottom
if (la >= 0 && lb >= 0) {
return la - lb;
}
// 4: none is first
if (fa < 0 && fb < 0 && la < 0 && lb < 0) {
// natural compare in the middle
return a < b ? -1 : 1;
}
// 6: one shoud go to top
if (fb >= 0) {
// b is first
return 1;
}
if (fa >= 0) {
// b is first
return -1;
}
// 5: at the end
if (lb >= 0) {
return -1;
}
if (la >= 0) {
return 1;
}
throw new Error('bug in sorter');
}
exports.k8sKeySort = k8sKeySort;
function isNameValid(name) {
return validName.test(name);
}
exports.isNameValid = isNameValid;
/**
* @param {string} str - the string to check for Base64 validity.
*
* Checks if the provided string is a valid Base64-encoded value by decoding it
* and comparing the re-encoded result to the original input.
*
* @returns {boolean} True if the input is valid Base64, false otherwise.
*/
function isBase64(str) {
// Attempt to decode the input string from Base64 into a buffer
try {
// Decode the input string using Base64
const buf = Buffer.from(str, 'base64');
// Buffer.from won’t throw on invalid input, so we compare the re-encoded buffer to the original string to verify validity
return buf.toString('base64') === str;
}
catch (_a) {
// Return false when decoding fails
return false;
}
}
exports.isBase64 = isBase64;
//# sourceMappingURL=format.js.map