webextensions-api-mock
Version:
WebExtensions API as sinon stubs
88 lines (86 loc) • 3.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = require("./helper");
const namespaces_walker_1 = require("./namespaces-walker");
const OUT_PREFIX = `
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/* eslint-disable @typescript-eslint/no-explicit-any */
import sinon from 'sinon';
`;
class NamespacesGenerator {
constructor(namespaces) {
this.outNamespaces = new Map();
this.outBrowser = new Map([
['sinonSandbox', 'sinon.SinonSandbox;'],
]);
this.imports = [];
this.namespaces = namespaces;
}
out() {
const schemaWalker = new namespaces_walker_1.NamespacesSchemaWalker(this.outNamespaces, this.imports);
schemaWalker.walk(this.namespaces);
this.addNestedInterfaceProperties(this.namespaces);
return this.buildOut();
}
// Add interfaces as properties of browser and of parent interfaces.
addNestedInterfaceProperties(schemaNamespaces) {
Object.values(schemaNamespaces).forEach(namespaces => namespaces.forEach(namespace => {
const nameParts = namespace.namespace.split('.');
const [topLevelName] = nameParts;
if (!this.outBrowser.has(topLevelName)) {
this.outBrowser.set(topLevelName, helper_1.capitalize(topLevelName));
}
if (nameParts.length > 1) {
let lastName = '';
nameParts.forEach((namePart, index) => {
var _a;
if (index > 0) {
(_a = this.outNamespaces
.get(lastName)) === null || _a === void 0 ? void 0 : _a.parent.push(`${namePart}: ${lastName + helper_1.capitalize(namePart)};`);
}
lastName += helper_1.capitalize(namePart);
});
}
}));
}
buildOut() {
const out = [OUT_PREFIX];
out.push(`export interface BrowserMock {`);
Array.from(this.outBrowser.keys())
.sort()
.forEach(key => {
const value = this.outBrowser.get(key);
out.push(`${key}: ${value}`);
});
out.push(`}\n`);
// For sorting interfaces/types by name
const typescriptsByName = new Map();
this.outNamespaces.forEach((outInterface, interfaceName) => {
const out = [];
out.push(`export interface ${interfaceName} {`);
outInterface.parent.sort().forEach(value => {
if (value.startsWith('eval:')) {
out.push('// @ts-ignore');
}
out.push(value);
});
out.push(`}\n`);
typescriptsByName.set(interfaceName, out.join('\n'));
outInterface.childTypes.sort().forEach(value => {
typescriptsByName.set(value, `export type ${value}\n`);
});
});
this.imports
.sort()
.forEach(nsImport => typescriptsByName.set(nsImport.name, `export type ${nsImport.name} = ${nsImport.import};`));
// Generate output from sorted interfaces/types
Array.from(typescriptsByName.keys())
.sort()
.forEach(key => {
const typescript = typescriptsByName.get(key);
out.push(`${typescript}\n`);
});
return out.join('\n');
}
}
exports.NamespacesGenerator = NamespacesGenerator;