New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@hyperone/cli-ext-root-openapi-generator

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hyperone/cli-ext-root-openapi-generator - npm Package Compare versions

Comparing version 1.0.6 to 1.0.7

1103

dist/index.js

@@ -1,1102 +0,1 @@

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 4);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("@hyperone/cli-core");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("@hyperone/cli-framework");
/***/ }),
/* 2 */
/***/ (function(module) {
module.exports = JSON.parse("{\"name\":\"@hyperone/cli-ext-root-openapi-generator\",\"version\":\"1.0.6\",\"description\":\"\",\"main\":\"dist/index.js\",\"browser\":\"index.js\",\"scripts\":{\"prepack\":\"NODE_ENV=production webpack\",\"build\":\"webpack\",\"watch\":\"webpack --watch\",\"clean\":\"rm dist -rf\"},\"devDependencies\":{\"webpack\":\"^4.43.0\",\"webpack-cli\":\"^3.3.12\",\"webpack-dev-server\":\"^3.11.0\"},\"author\":\"Adam Dobrawy\",\"license\":\"MIT\",\"dependencies\":{\"@hyperone/cli-core\":\"^1.0.6\",\"@hyperone/cli-framework\":\"^1.0.6\",\"jsonpatch\":\"^3.0.1\",\"openapi-sampler\":\"^1.0.0-beta.16\",\"pluralize\":\"^8.0.0\"},\"gitHead\":\"d5723dcb3a1caf0442196a7fc2abe041241813f0\",\"publishConfig\":{\"access\":\"public\"}}");
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* global define */
(function (root, pluralize) {
/* istanbul ignore else */
if (true) {
// Node.
module.exports = pluralize();
} else {}
})(this, function () {
// Rule storage - pluralize and singularize need to be run sequentially,
// while other rules can be optimized using an object for instant lookups.
var pluralRules = [];
var singularRules = [];
var uncountables = {};
var irregularPlurals = {};
var irregularSingles = {};
/**
* Sanitize a pluralization rule to a usable regular expression.
*
* @param {(RegExp|string)} rule
* @return {RegExp}
*/
function sanitizeRule (rule) {
if (typeof rule === 'string') {
return new RegExp('^' + rule + '$', 'i');
}
return rule;
}
/**
* Pass in a word token to produce a function that can replicate the case on
* another word.
*
* @param {string} word
* @param {string} token
* @return {Function}
*/
function restoreCase (word, token) {
// Tokens are an exact match.
if (word === token) return token;
// Lower cased words. E.g. "hello".
if (word === word.toLowerCase()) return token.toLowerCase();
// Upper cased words. E.g. "WHISKY".
if (word === word.toUpperCase()) return token.toUpperCase();
// Title cased words. E.g. "Title".
if (word[0] === word[0].toUpperCase()) {
return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
}
// Lower cased words. E.g. "test".
return token.toLowerCase();
}
/**
* Interpolate a regexp string.
*
* @param {string} str
* @param {Array} args
* @return {string}
*/
function interpolate (str, args) {
return str.replace(/\$(\d{1,2})/g, function (match, index) {
return args[index] || '';
});
}
/**
* Replace a word using a rule.
*
* @param {string} word
* @param {Array} rule
* @return {string}
*/
function replace (word, rule) {
return word.replace(rule[0], function (match, index) {
var result = interpolate(rule[1], arguments);
if (match === '') {
return restoreCase(word[index - 1], result);
}
return restoreCase(match, result);
});
}
/**
* Sanitize a word by passing in the word and sanitization rules.
*
* @param {string} token
* @param {string} word
* @param {Array} rules
* @return {string}
*/
function sanitizeWord (token, word, rules) {
// Empty string or doesn't need fixing.
if (!token.length || uncountables.hasOwnProperty(token)) {
return word;
}
var len = rules.length;
// Iterate over the sanitization rules and use the first one to match.
while (len--) {
var rule = rules[len];
if (rule[0].test(word)) return replace(word, rule);
}
return word;
}
/**
* Replace a word with the updated word.
*
* @param {Object} replaceMap
* @param {Object} keepMap
* @param {Array} rules
* @return {Function}
*/
function replaceWord (replaceMap, keepMap, rules) {
return function (word) {
// Get the correct token and case restoration functions.
var token = word.toLowerCase();
// Check against the keep object map.
if (keepMap.hasOwnProperty(token)) {
return restoreCase(word, token);
}
// Check against the replacement map for a direct word replacement.
if (replaceMap.hasOwnProperty(token)) {
return restoreCase(word, replaceMap[token]);
}
// Run all the rules against the word.
return sanitizeWord(token, word, rules);
};
}
/**
* Check if a word is part of the map.
*/
function checkWord (replaceMap, keepMap, rules, bool) {
return function (word) {
var token = word.toLowerCase();
if (keepMap.hasOwnProperty(token)) return true;
if (replaceMap.hasOwnProperty(token)) return false;
return sanitizeWord(token, token, rules) === token;
};
}
/**
* Pluralize or singularize a word based on the passed in count.
*
* @param {string} word The word to pluralize
* @param {number} count How many of the word exist
* @param {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks)
* @return {string}
*/
function pluralize (word, count, inclusive) {
var pluralized = count === 1
? pluralize.singular(word) : pluralize.plural(word);
return (inclusive ? count + ' ' : '') + pluralized;
}
/**
* Pluralize a word.
*
* @type {Function}
*/
pluralize.plural = replaceWord(
irregularSingles, irregularPlurals, pluralRules
);
/**
* Check if a word is plural.
*
* @type {Function}
*/
pluralize.isPlural = checkWord(
irregularSingles, irregularPlurals, pluralRules
);
/**
* Singularize a word.
*
* @type {Function}
*/
pluralize.singular = replaceWord(
irregularPlurals, irregularSingles, singularRules
);
/**
* Check if a word is singular.
*
* @type {Function}
*/
pluralize.isSingular = checkWord(
irregularPlurals, irregularSingles, singularRules
);
/**
* Add a pluralization rule to the collection.
*
* @param {(string|RegExp)} rule
* @param {string} replacement
*/
pluralize.addPluralRule = function (rule, replacement) {
pluralRules.push([sanitizeRule(rule), replacement]);
};
/**
* Add a singularization rule to the collection.
*
* @param {(string|RegExp)} rule
* @param {string} replacement
*/
pluralize.addSingularRule = function (rule, replacement) {
singularRules.push([sanitizeRule(rule), replacement]);
};
/**
* Add an uncountable word rule.
*
* @param {(string|RegExp)} word
*/
pluralize.addUncountableRule = function (word) {
if (typeof word === 'string') {
uncountables[word.toLowerCase()] = true;
return;
}
// Set singular and plural references for the word.
pluralize.addPluralRule(word, '$0');
pluralize.addSingularRule(word, '$0');
};
/**
* Add an irregular word definition.
*
* @param {string} single
* @param {string} plural
*/
pluralize.addIrregularRule = function (single, plural) {
plural = plural.toLowerCase();
single = single.toLowerCase();
irregularSingles[single] = plural;
irregularPlurals[plural] = single;
};
/**
* Irregular rules.
*/
[
// Pronouns.
['I', 'we'],
['me', 'us'],
['he', 'they'],
['she', 'they'],
['them', 'them'],
['myself', 'ourselves'],
['yourself', 'yourselves'],
['itself', 'themselves'],
['herself', 'themselves'],
['himself', 'themselves'],
['themself', 'themselves'],
['is', 'are'],
['was', 'were'],
['has', 'have'],
['this', 'these'],
['that', 'those'],
// Words ending in with a consonant and `o`.
['echo', 'echoes'],
['dingo', 'dingoes'],
['volcano', 'volcanoes'],
['tornado', 'tornadoes'],
['torpedo', 'torpedoes'],
// Ends with `us`.
['genus', 'genera'],
['viscus', 'viscera'],
// Ends with `ma`.
['stigma', 'stigmata'],
['stoma', 'stomata'],
['dogma', 'dogmata'],
['lemma', 'lemmata'],
['schema', 'schemata'],
['anathema', 'anathemata'],
// Other irregular rules.
['ox', 'oxen'],
['axe', 'axes'],
['die', 'dice'],
['yes', 'yeses'],
['foot', 'feet'],
['eave', 'eaves'],
['goose', 'geese'],
['tooth', 'teeth'],
['quiz', 'quizzes'],
['human', 'humans'],
['proof', 'proofs'],
['carve', 'carves'],
['valve', 'valves'],
['looey', 'looies'],
['thief', 'thieves'],
['groove', 'grooves'],
['pickaxe', 'pickaxes'],
['passerby', 'passersby']
].forEach(function (rule) {
return pluralize.addIrregularRule(rule[0], rule[1]);
});
/**
* Pluralization rules.
*/
[
[/s?$/i, 's'],
[/[^\u0000-\u007F]$/i, '$0'],
[/([^aeiou]ese)$/i, '$1'],
[/(ax|test)is$/i, '$1es'],
[/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],
[/(e[mn]u)s?$/i, '$1s'],
[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],
[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
[/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
[/(seraph|cherub)(?:im)?$/i, '$1im'],
[/(her|at|gr)o$/i, '$1oes'],
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/([^ch][ieo][ln])ey$/i, '$1ies'],
[/(x|ch|ss|sh|zz)$/i, '$1es'],
[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
[/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],
[/(pe)(?:rson|ople)$/i, '$1ople'],
[/(child)(?:ren)?$/i, '$1ren'],
[/eaux$/i, '$0'],
[/m[ae]n$/i, 'men'],
['thou', 'you']
].forEach(function (rule) {
return pluralize.addPluralRule(rule[0], rule[1]);
});
/**
* Singularization rules.
*/
[
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
[/ies$/i, 'y'],
[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],
[/\b(mon|smil)ies$/i, '$1ey'],
[/\b((?:tit)?m|l)ice$/i, '$1ouse'],
[/(seraph|cherub)im$/i, '$1'],
[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'],
[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'],
[/(movie|twelve|abuse|e[mn]u)s$/i, '$1'],
[/(test)(?:is|es)$/i, '$1is'],
[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
[/(alumn|alg|vertebr)ae$/i, '$1a'],
[/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
[/(matr|append)ices$/i, '$1ix'],
[/(pe)(rson|ople)$/i, '$1rson'],
[/(child)ren$/i, '$1'],
[/(eau)x?$/i, '$1'],
[/men$/i, 'man']
].forEach(function (rule) {
return pluralize.addSingularRule(rule[0], rule[1]);
});
/**
* Uncountable rules.
*/
[
// Singular words with no plurals.
'adulthood',
'advice',
'agenda',
'aid',
'aircraft',
'alcohol',
'ammo',
'analytics',
'anime',
'athletics',
'audio',
'bison',
'blood',
'bream',
'buffalo',
'butter',
'carp',
'cash',
'chassis',
'chess',
'clothing',
'cod',
'commerce',
'cooperation',
'corps',
'debris',
'diabetes',
'digestion',
'elk',
'energy',
'equipment',
'excretion',
'expertise',
'firmware',
'flounder',
'fun',
'gallows',
'garbage',
'graffiti',
'hardware',
'headquarters',
'health',
'herpes',
'highjinks',
'homework',
'housework',
'information',
'jeans',
'justice',
'kudos',
'labour',
'literature',
'machinery',
'mackerel',
'mail',
'media',
'mews',
'moose',
'music',
'mud',
'manga',
'news',
'only',
'personnel',
'pike',
'plankton',
'pliers',
'police',
'pollution',
'premises',
'rain',
'research',
'rice',
'salmon',
'scissors',
'series',
'sewage',
'shambles',
'shrimp',
'software',
'species',
'staff',
'swine',
'tennis',
'traffic',
'transportation',
'trout',
'tuna',
'wealth',
'welfare',
'whiting',
'wildebeest',
'wildlife',
'you',
/pok[eé]mon$/i,
// Regexes.
/[^aeiou]ese$/i, // "chinese", "japanese"
/deer$/i, // "deer", "reindeer"
/fish$/i, // "fish", "blowfish", "angelfish"
/measles$/i,
/o[iu]s$/i, // "carnivorous"
/pox$/i, // "chickpox", "smallpox"
/sheep$/i
].forEach(pluralize.addUncountableRule);
return pluralize;
});
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: /home/adas/Devel/h1-cli-v2/node_modules/pluralize/pluralize.js
var pluralize = __webpack_require__(3);
var pluralize_default = /*#__PURE__*/__webpack_require__.n(pluralize);
// EXTERNAL MODULE: external "@hyperone/cli-framework"
var cli_framework_ = __webpack_require__(1);
// EXTERNAL MODULE: external "@hyperone/cli-core"
var cli_core_ = __webpack_require__(0);
// CONCATENATED MODULE: /home/adas/Devel/h1-cli-v2/packages/cli-core/lib/transform.js
const deCamelCase = (text) => String(text)
.replace(/([a-z])([A-Z])/, (m, a, b) => `${a}-${b}`)
.toLowerCase();
const get = (obj, path, defaultValue) => {
const result = String.prototype.split.call(path, /[,[\].]+?/)
.filter(Boolean)
.reduce((res, key) => res !== null && res !== undefined ? res[key] : res, obj);
return result === undefined || result === obj ? defaultValue : result;
};
const set = (obj, path, value) => {
const keys = String.prototype.split.call(path, /[,[\].]+?/).filter(Boolean);
let el = obj;
for (const key of keys.slice(0, -1)) {
if (el[key] === undefined) {
el[key] = {};
}
el = el[key];
}
el[keys[keys.length - 1]] = value;
};
const unset = (obj, path) => set(obj, path, undefined);
// CONCATENATED MODULE: /home/adas/Devel/h1-cli-v2/packages/cli-core/types.js
const extractId = (value) => {
if (value.startsWith('/')) return value.split('/').pop();
return value;
};
const nestedValue = value => {
const result = {};
for (const v of value.split(',')) {
const [pkey, pvalue] = v.split(/=/, 2);
result[pkey] = pvalue;
}
return result;
};
/* harmony default export */ var types = ({
extractId,
nestedValue,
});
// CONCATENATED MODULE: ./request.js
const idless = (name) => name.replace(/Id$/, '');
const parameterForParameter = (p = []) => {
const parameters = [];
for (const parameter of p) {
const name = idless(parameter.name);
const description = [
parameter.description,
];
const p = {
name: deCamelCase(name),
use: {
in: 'path',
field: parameter.name,
},
};
if (parameter.name.endsWith('Id')) {
Object.assign(p, {
required: true,
defaultSource: name,
type: types.extractId,
typeLabel: 'id-or-uri',
});
}
parameters.push({
...p,
description: description.join('.'),
});
}
return parameters;
};
const parameterForSchema = (schema, prefix = '', path = '') => {
const parameters = [];
for (const [pname, pvalue] of Object.entries(schema.properties || {})) {
const description = [];
const required = schema.required || [];
const p = {
name: `${prefix}${deCamelCase(pname)}`,
required: required.includes(pname),
use: {
in: 'body',
field: `${path}/${pname}`,
},
};
if (pvalue.title) {
description.push(pvalue.title);
}
if (pvalue.readOnly) {
continue;
}
// TODO: Remove audiance support
const audience = pvalue['x-audience'];
if (audience && !['user', 'all'].includes(audience)) {
continue;
}
if (pvalue['x-resource']) {
Object.assign(p, {
typeLabel: 'uri',
});
const prefixes = cli_core_["openapi"].getEndpointForKind(pvalue['x-resource'].kind);
if (prefixes.length == 1) {
Object.assign(p, {
typeLabel: 'id-or-uri',
prefix: prefixes[0],
});
description.push(`Provide ID or URI of ${pvalue['x-resource'].kind}`);
} else {
description.push(`Provide URI of ${pvalue['x-resource'].kind}`);
}
}
if (pvalue['x-permissions']) {
description.push(`Requires permissions ${pvalue['x-permissions'].join(', ')}`);
}
if (pvalue.type == 'string') {
Object.assign(p, {
placeholder: pname,
});
}
if (pvalue.type == 'array' && pvalue.items.type == 'string') {
Object.assign(p, {
multiple: true,
});
}
if (pvalue.type == 'boolean') {
const choices = [true, false].map(String);
Object.assign(p, {
type: (value) => value == 'true',
typeLabel: choices.join(','),
choices,
});
}
if (pvalue.type == 'object') {
parameters.push(
...parameterForSchema(
pvalue,
!!prefix ? `${prefix}-${pname}` : `${pname}-`,
`${path}/${pname}`
)
);
continue;
}
if (pvalue.type == 'array' && pvalue.items.type == 'object') {
const label = Object.entries(pvalue.items.properties || {})
.filter(([, value]) => value.readOnly != true)
.map(([key]) => `${key}=${key}`)
.join(',');
Object.assign(p, {
multiple: true,
typeLabel: label,
type: types.nestedValue,
});
}
if (pvalue.default) {
description.push(`Defaults is ${pvalue.default}`);
Object.assign(p, {
defaultValue: pvalue.default,
});
}
Object.assign(p, {
description: description.join('. '),
});
parameters.push(p);
}
return parameters;
};
const renderOptions = (operation) => {
const schema = cli_core_["openapi"].getSchema(operation);
const parameters = [
...parameterForParameter(operation.parameters),
...parameterForSchema(schema),
];
return parameters;
};
const renderBody = (operation, input, options) => {
const result = {};
for (const option of options) {
if (!option.use || option.use.in != 'body') {
continue;
}
let value = input[option.name];
if (option.prefix && value && !value.startsWith('/')) {
value = renderPath(option.prefix, operation, input);
}
set(result, option.use.field.replace(/\//g, '.'), value);
}
return result;
};
const renderQuery = (path, operation) => {
const schema = cli_core_["openapi"].getResponse(operation) || {};
const col = [];
let props;
if (schema.type == 'array') {
props = schema.items.properties || {};
} else if (schema.type == 'object') {
props = schema.properties || {};
}
if (props) {
for (const name of ['id', 'name', 'state', 'flavour', 'content', 'enabled', 'size']) {
if (props[name]) {
col.push(`${name}:${name}`);
}
}
}
if (col.length == 0) {
col.push('value:@');
}
return `[].{${col.join(',')}}`;
};
const renderPath = (path, operation, input) => {
let url = path;
for (const [pattern, , key] of url.matchAll('\{((.+?)Id)\}')) {
url = url.replace(pattern, input[key]);
}
return url;
};
/* harmony default export */ var request = ({
renderOptions,
renderBody,
renderPath,
renderQuery,
});
// CONCATENATED MODULE: ./index.js
const printCommand = (name, content) => new cli_framework_["Command"]({
name,
summary: 'Print specification of context',
handler: () => content,
});
const makeOperationCommand = ({ name, operation, method, path }) => () => {
const options = request.renderOptions(operation);
return new cli_framework_["Command"]({
name,
summary: `${operation.summary} [${operation.operationId}]`,
options,
tags: [operation.operationId],
handler: async (opts) => {
const optsAll = opts._all || opts;
const url = cli_core_["openapi"].getUrl(request.renderPath(path, operation, optsAll));
const body = request.renderBody(operation, optsAll, options);
opts.defaultQuery = request.renderQuery(path, operation, optsAll);
const resp = await opts.api[method](url, body);
return opts.format(opts, resp);
},
});
};
const makeResourceCommand = (resource, ctx) => () => {
const cmd = new cli_framework_["Category"]({
name: resource.type,
summary: ctx.description || `Management of ${resource.type} resource`,
});
cmd.addCommand(printCommand('spec', ctx));
const collectionOperation = cli_core_["openapi"].getPath(ctx.path) || {};
if (collectionOperation) {
if (collectionOperation.post) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'create',
method: 'post',
operation: collectionOperation.post,
})
);
}
if (collectionOperation.get) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'list',
method: 'get',
operation: collectionOperation.get,
})
);
}
if (collectionOperation.patch) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'update',
method: 'patch',
operation: collectionOperation.patch,
})
);
}
}
const instancePathPrefix = `${ctx.path}/{${resource.type}Id}`;
const instanceOperation = cli_core_["openapi"].getPath(instancePathPrefix) || {};
if (instanceOperation) {
if (instanceOperation.get) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'show',
method: 'get',
operation: instanceOperation.get,
path: instancePathPrefix,
})
);
}
if (instanceOperation.patch) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'update',
method: 'patch',
operation: instanceOperation.patch,
path: instancePathPrefix,
})
);
}
if (instanceOperation.delete) {
cmd.addCommand(
makeOperationCommand({
...ctx,
name: 'delete',
method: 'delete',
operation: instanceOperation.delete,
path: instancePathPrefix,
})
);
}
}
for (const { name, path } of cli_core_["openapi"].getActions(instancePathPrefix)) {
cmd.addCommand(makeOperationCommand({
...ctx,
name,
method: 'post',
operation: cli_core_["openapi"].getPath(path).post,
path,
}));
}
for (const child of cli_core_["openapi"].getChild(instancePathPrefix)) {
cmd.addCommand(makeResourceCommand(child, {
path: child.path,
description: `Manage ${pluralize_default()(child.type)} of the ${resource.type}`,
}));
}
return cmd;
};
const buildNamespaceCommand = (name, spec, ctx) => async () => {
const cmd = new cli_framework_["Category"]({
name,
summary: `Management of ${name} namespace`,
extensions: [`@hyperone/cli-ext-${name}`],
});
cmd.addCommand(printCommand('spec', spec, ctx));
const parent_cmds = {};
for (const resource of spec) {
let path = ctx.path;
if (resource.location) {
path = `${path}/{locationId}`;
}
// Custom logic for resource in multiple namespaces
// Example for "iam/policy":
// iam policy - for policy of project
// iam policy organisation - for policy of project
// Example for "website/instance":
// website instance - for instance of project
// Future proof, adding new resources at any level
if (resource.parent) {
for (const parent of resource.parent) {
let parent_cmd;
if (parent == 'project') {
parent_cmd = cmd;
} else {
parent_cmds[parent] = parent_cmds[parent] || new cli_framework_["Category"]({
name: parent,
summary: `Management of ${parent}`,
});
parent_cmd = parent_cmds[parent];
}
parent_cmd.addCommand(makeResourceCommand(resource, {
...ctx,
path: `${path}/${parent}/{${parent}Id}/${resource.type}`,
}));
}
} else {
cmd.addCommand(makeResourceCommand(resource, {
...ctx,
path: `${path}/${resource.type}`,
}));
}
}
cmd.addCommand(...Object.values(parent_cmds));
// fs.subdirectories(directory, false, options.matching)
return cmd;
};
/* harmony default export */ var index = __webpack_exports__["default"] = ({
name: __webpack_require__(2).name,
version: __webpack_require__(2).version,
load: async (parent) => {
const namespaces = cli_core_["openapi"].getNamespaces();
for (const [name, spec] of Object.entries(namespaces)) {
await parent.addCommand(buildNamespaceCommand(name, spec, {
path: `/${name}`,
}));
}
},
});
/***/ })
/******/ ]);
module.exports=function(e){var t={};function a(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,a),o.l=!0,o.exports}return a.m=e,a.c=t,a.d=function(e,t,r){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)a.d(r,o,function(t){return e[t]}.bind(null,o));return r},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="",a(a.s=4)}([function(e,t){e.exports=require("@hyperone/cli-core")},function(e,t){e.exports=require("@hyperone/cli-framework")},function(e){e.exports=JSON.parse('{"name":"@hyperone/cli-ext-root-openapi-generator","version":"1.0.7","description":"","main":"dist/index.js","browser":"index.js","scripts":{"prepack":"NODE_ENV=production webpack","build":"webpack","watch":"webpack --watch","clean":"rm dist -rf"},"devDependencies":{"webpack":"^4.43.0","webpack-cli":"^3.3.12","webpack-dev-server":"^3.11.0"},"author":"Adam Dobrawy","license":"MIT","dependencies":{"@hyperone/cli-core":"^1.0.7","@hyperone/cli-framework":"^1.0.6","jsonpatch":"^3.0.1","openapi-sampler":"^1.0.0-beta.16","pluralize":"^8.0.0"},"gitHead":"b51a930fcf67d351fb8243c40b64e8e17d80c10b","publishConfig":{"access":"public"}}')},function(e,t,a){e.exports=function(){var e=[],t=[],a={},r={},o={};function n(e){return"string"==typeof e?new RegExp("^"+e+"$","i"):e}function i(e,t){return e===t?t:e===e.toLowerCase()?t.toLowerCase():e===e.toUpperCase()?t.toUpperCase():e[0]===e[0].toUpperCase()?t.charAt(0).toUpperCase()+t.substr(1).toLowerCase():t.toLowerCase()}function s(e,t){return e.replace(/\$(\d{1,2})/g,(function(e,a){return t[a]||""}))}function u(e,t){return e.replace(t[0],(function(a,r){var o=s(t[1],arguments);return i(""===a?e[r-1]:a,o)}))}function c(e,t,r){if(!e.length||a.hasOwnProperty(e))return t;for(var o=r.length;o--;){var n=r[o];if(n[0].test(t))return u(t,n)}return t}function l(e,t,a){return function(r){var o=r.toLowerCase();return t.hasOwnProperty(o)?i(r,o):e.hasOwnProperty(o)?i(r,e[o]):c(o,r,a)}}function p(e,t,a,r){return function(r){var o=r.toLowerCase();return!!t.hasOwnProperty(o)||!e.hasOwnProperty(o)&&c(o,o,a)===o}}function d(e,t,a){return(a?t+" ":"")+(1===t?d.singular(e):d.plural(e))}return d.plural=l(o,r,e),d.isPlural=p(o,r,e),d.singular=l(r,o,t),d.isSingular=p(r,o,t),d.addPluralRule=function(t,a){e.push([n(t),a])},d.addSingularRule=function(e,a){t.push([n(e),a])},d.addUncountableRule=function(e){"string"!=typeof e?(d.addPluralRule(e,"$0"),d.addSingularRule(e,"$0")):a[e.toLowerCase()]=!0},d.addIrregularRule=function(e,t){t=t.toLowerCase(),e=e.toLowerCase(),o[e]=t,r[t]=e},[["I","we"],["me","us"],["he","they"],["she","they"],["them","them"],["myself","ourselves"],["yourself","yourselves"],["itself","themselves"],["herself","themselves"],["himself","themselves"],["themself","themselves"],["is","are"],["was","were"],["has","have"],["this","these"],["that","those"],["echo","echoes"],["dingo","dingoes"],["volcano","volcanoes"],["tornado","tornadoes"],["torpedo","torpedoes"],["genus","genera"],["viscus","viscera"],["stigma","stigmata"],["stoma","stomata"],["dogma","dogmata"],["lemma","lemmata"],["schema","schemata"],["anathema","anathemata"],["ox","oxen"],["axe","axes"],["die","dice"],["yes","yeses"],["foot","feet"],["eave","eaves"],["goose","geese"],["tooth","teeth"],["quiz","quizzes"],["human","humans"],["proof","proofs"],["carve","carves"],["valve","valves"],["looey","looies"],["thief","thieves"],["groove","grooves"],["pickaxe","pickaxes"],["passerby","passersby"]].forEach((function(e){return d.addIrregularRule(e[0],e[1])})),[[/s?$/i,"s"],[/[^\u0000-\u007F]$/i,"$0"],[/([^aeiou]ese)$/i,"$1"],[/(ax|test)is$/i,"$1es"],[/(alias|[^aou]us|t[lm]as|gas|ris)$/i,"$1es"],[/(e[mn]u)s?$/i,"$1s"],[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,"$1"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1i"],[/(alumn|alg|vertebr)(?:a|ae)$/i,"$1ae"],[/(seraph|cherub)(?:im)?$/i,"$1im"],[/(her|at|gr)o$/i,"$1oes"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,"$1a"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,"$1a"],[/sis$/i,"ses"],[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,"$1$2ves"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/([^ch][ieo][ln])ey$/i,"$1ies"],[/(x|ch|ss|sh|zz)$/i,"$1es"],[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,"$1ices"],[/\b((?:tit)?m|l)(?:ice|ouse)$/i,"$1ice"],[/(pe)(?:rson|ople)$/i,"$1ople"],[/(child)(?:ren)?$/i,"$1ren"],[/eaux$/i,"$0"],[/m[ae]n$/i,"men"],["thou","you"]].forEach((function(e){return d.addPluralRule(e[0],e[1])})),[[/s$/i,""],[/(ss)$/i,"$1"],[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,"$1fe"],[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i,"$1f"],[/ies$/i,"y"],[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i,"$1ie"],[/\b(mon|smil)ies$/i,"$1ey"],[/\b((?:tit)?m|l)ice$/i,"$1ouse"],[/(seraph|cherub)im$/i,"$1"],[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,"$1"],[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,"$1sis"],[/(movie|twelve|abuse|e[mn]u)s$/i,"$1"],[/(test)(?:is|es)$/i,"$1is"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1us"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,"$1um"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,"$1on"],[/(alumn|alg|vertebr)ae$/i,"$1a"],[/(cod|mur|sil|vert|ind)ices$/i,"$1ex"],[/(matr|append)ices$/i,"$1ix"],[/(pe)(rson|ople)$/i,"$1rson"],[/(child)ren$/i,"$1"],[/(eau)x?$/i,"$1"],[/men$/i,"man"]].forEach((function(e){return d.addSingularRule(e[0],e[1])})),["adulthood","advice","agenda","aid","aircraft","alcohol","ammo","analytics","anime","athletics","audio","bison","blood","bream","buffalo","butter","carp","cash","chassis","chess","clothing","cod","commerce","cooperation","corps","debris","diabetes","digestion","elk","energy","equipment","excretion","expertise","firmware","flounder","fun","gallows","garbage","graffiti","hardware","headquarters","health","herpes","highjinks","homework","housework","information","jeans","justice","kudos","labour","literature","machinery","mackerel","mail","media","mews","moose","music","mud","manga","news","only","personnel","pike","plankton","pliers","police","pollution","premises","rain","research","rice","salmon","scissors","series","sewage","shambles","shrimp","software","species","staff","swine","tennis","traffic","transportation","trout","tuna","wealth","welfare","whiting","wildebeest","wildlife","you",/pok[eé]mon$/i,/[^aeiou]ese$/i,/deer$/i,/fish$/i,/measles$/i,/o[iu]s$/i,/pox$/i,/sheep$/i].forEach(d.addUncountableRule),d}()},function(e,t,a){"use strict";a.r(t);var r=a(3),o=a.n(r),n=a(1),i=a(0);const s=e=>String(e).replace(/([a-z])([A-Z])/,(e,t,a)=>`${t}-${a}`).toLowerCase(),u=(e,t,a)=>{const r=String.prototype.split.call(t,/[,[\].]+?/).filter(Boolean);let o=e;for(const e of r.slice(0,-1))void 0===o[e]&&(o[e]={}),o=o[e];o[r[r.length-1]]=a};var c={extractId:e=>e.startsWith("/")?e.split("/").pop():e,nestedValue:e=>{const t={};for(const a of e.split(",")){const[e,r]=a.split(/=/,2);t[e]=r}return t}};const l=e=>e.replace(/Id$/,""),p=(e=[])=>{const t=[];for(const a of e){const e=l(a.name),r=[a.description],o={name:s(e),use:{in:"path",field:a.name}};a.name.endsWith("Id")&&Object.assign(o,{required:!0,defaultSource:e,type:c.extractId,typeLabel:"id-or-uri"}),t.push({...o,description:r.join(".")})}return t},d=(e,t="",a="")=>{const r=[];for(const[o,n]of Object.entries(e.properties||{})){const u=[],l=e.required||[],p={name:`${t}${s(o)}`,required:l.includes(o),use:{in:"body",field:`${a}/${o}`}};if(n.title&&u.push(n.title),n.readOnly)continue;const m=n["x-audience"];if(!m||["user","all"].includes(m)){if(n["x-resource"]){Object.assign(p,{typeLabel:"uri"});const e=i.openapi.getEndpointForKind(n["x-resource"].kind);1==e.length?(Object.assign(p,{typeLabel:"id-or-uri",prefix:e[0]}),u.push("Provide ID or URI of "+n["x-resource"].kind)):u.push("Provide URI of "+n["x-resource"].kind)}if(n["x-permissions"]&&u.push("Requires permissions "+n["x-permissions"].join(", ")),"string"==n.type&&Object.assign(p,{placeholder:o}),"array"==n.type&&"string"==n.items.type&&Object.assign(p,{multiple:!0}),"boolean"==n.type){const e=[!0,!1].map(String);Object.assign(p,{type:e=>"true"==e,typeLabel:e.join(","),choices:e})}if("object"!=n.type){if("array"==n.type&&"object"==n.items.type){const e=Object.entries(n.items.properties||{}).filter(([,e])=>1!=e.readOnly).map(([e])=>`${e}=${e}`).join(",");Object.assign(p,{multiple:!0,typeLabel:e,type:c.nestedValue})}n.default&&(u.push("Defaults is "+n.default),Object.assign(p,{defaultValue:n.default})),Object.assign(p,{description:u.join(". ")}),r.push(p)}else r.push(...d(n,t?`${t}-${o}`:o+"-",`${a}/${o}`))}}return r},m=(e,t,a)=>{let r=e;for(const[e,,t]of r.matchAll("{((.+?)Id)}"))r=r.replace(e,a[t]);return r};var h={renderOptions:e=>{const t=i.openapi.getSchema(e);return[...p(e.parameters),...d(t)]},renderBody:(e,t,a)=>{const r={};for(const o of a){if(!o.use||"body"!=o.use.in)continue;let a=t[o.name];o.prefix&&a&&!a.startsWith("/")&&(a=m(o.prefix,e,t)),u(r,o.use.field.replace(/\//g,"."),a)}return r},renderPath:m,renderQuery:(e,t)=>{const a=i.openapi.getResponse(t)||{},r=[];let o;if("array"==a.type?o=a.items.properties||{}:"object"==a.type&&(o=a.properties||{}),o)for(const e of["id","name","state","flavour","content","enabled","size"])o[e]&&r.push(`${e}:${e}`);return 0==r.length&&r.push("value:@"),`[].{${r.join(",")}}`}};const f=(e,t)=>new n.Command({name:e,summary:"Print specification of context",handler:()=>t}),$=({name:e,operation:t,method:a,path:r})=>()=>{const o=h.renderOptions(t);return new n.Command({name:e,summary:`${t.summary} [${t.operationId}]`,options:o,tags:[t.operationId],handler:async e=>{const n=e._all||e,s=i.openapi.getUrl(h.renderPath(r,t,n)),u=h.renderBody(t,n,o);e.defaultQuery=h.renderQuery(r,t,n);const c=await e.api[a](s,u);return e.format(e,c)}})},g=(e,t)=>()=>{const a=new n.Category({name:e.type,summary:t.description||`Management of ${e.type} resource`});a.addCommand(f("spec",t));const r=i.openapi.getPath(t.path)||{};r&&(r.post&&a.addCommand($({...t,name:"create",method:"post",operation:r.post})),r.get&&a.addCommand($({...t,name:"list",method:"get",operation:r.get})),r.patch&&a.addCommand($({...t,name:"update",method:"patch",operation:r.patch})));const s=`${t.path}/{${e.type}Id}`,u=i.openapi.getPath(s)||{};u&&(u.get&&a.addCommand($({...t,name:"show",method:"get",operation:u.get,path:s})),u.patch&&a.addCommand($({...t,name:"update",method:"patch",operation:u.patch,path:s})),u.delete&&a.addCommand($({...t,name:"delete",method:"delete",operation:u.delete,path:s})));for(const{name:e,path:r}of i.openapi.getActions(s))a.addCommand($({...t,name:e,method:"post",operation:i.openapi.getPath(r).post,path:r}));for(const t of i.openapi.getChild(s))a.addCommand(g(t,{path:t.path,description:`Manage ${o()(t.type)} of the ${e.type}`}));return a},y=(e,t,a)=>async()=>{const r=new n.Category({name:e,summary:`Management of ${e} namespace`,extensions:["@hyperone/cli-ext-"+e]});r.addCommand(f("spec",t));const o={};for(const e of t){let t=a.path;if(e.location&&(t+="/{locationId}"),e.parent)for(const i of e.parent){let s;"project"==i?s=r:(o[i]=o[i]||new n.Category({name:i,summary:"Management of "+i}),s=o[i]),s.addCommand(g(e,{...a,path:`${t}/${i}/{${i}Id}/${e.type}`}))}else r.addCommand(g(e,{...a,path:`${t}/${e.type}`}))}return r.addCommand(...Object.values(o)),r};t.default={name:a(2).name,version:a(2).version,load:async e=>{const t=i.openapi.getNamespaces();for(const[a,r]of Object.entries(t))await e.addCommand(y(a,r,{path:"/"+a}))}}}]);

6

package.json
{
"name": "@hyperone/cli-ext-root-openapi-generator",
"version": "1.0.6",
"version": "1.0.7",
"description": "",

@@ -21,3 +21,3 @@ "main": "dist/index.js",

"dependencies": {
"@hyperone/cli-core": "^1.0.6",
"@hyperone/cli-core": "^1.0.7",
"@hyperone/cli-framework": "^1.0.6",

@@ -28,3 +28,3 @@ "jsonpatch": "^3.0.1",

},
"gitHead": "d5723dcb3a1caf0442196a7fc2abe041241813f0",
"gitHead": "b51a930fcf67d351fb8243c40b64e8e17d80c10b",
"publishConfig": {

@@ -31,0 +31,0 @@ "access": "public"

@@ -17,6 +17,7 @@

},
optimization: {
minimize: false, // see https://github.com/terser/terser/issues/764
externals: {
'@hyperone/cli-core':'commonjs2 @hyperone/cli-core',
'@hyperone/cli-framework':'commonjs2 @hyperone/cli-framework',
},
externals: ['@hyperone/cli-core', '@hyperone/cli-framework'],
};
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc